Python3登录12306购票网站教程

import re,requests,base64
def aui(indexs):
amap = {
‘1’: ‘34,40’,
‘2’: ‘111,43’,
‘3’: ‘180,40’,
‘4’: ‘254,40’,
‘5’: ‘34,120’,
‘6’: ‘111,120’,
‘7’: ‘180,120’,
‘8’: ‘254,120’,
}

temp =\[\]
for item in indexs:
    temp.append(amap\[item\])
return ','.join(temp)

session = requests.Session()
session.headers[‘User-Agent’] = ‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36’
session_url = ‘https://kyfw.12306.cn/otn/login/conf'
session.post(session_url)
captcha_url = ‘https://kyfw.12306.cn/passport/captcha/captcha-image64?login\_site=E&module=login&rand=sjrand&1542247405099&callback=jQuery19105989645797476608\_1542247401866&\_=1542247401867'
captcha_base64 = session.get(captcha_url)
captcha_encode = re.findall(r’”image”:”(.*?)”‘, captcha_base64.text)[0]
captcha_img = base64.b64decode(captcha_encode)
with open(‘captcha.png’, ‘wb’) as f:
f.write(captcha_img)
check_url = ‘https://kyfw.12306.cn/passport/captcha/captcha-check?callback=jQuery1910937049112524313\_1542250866358&rand=sjrand&login\_site=E&\_=1542250866360'

check_response = session.get(check_url,params={‘answer’:aui(input(‘请输入坐标图片序号:’))}) ###传入图片坐标
check_code = re.findall(r’”result_code”:”(\d)”‘,check_response.text)[0]
if check_code == ‘4’:
print(‘1.验证码效验成功’)
login_url = ‘https://kyfw.12306.cn/passport/web/login'
data_user = {
‘username’:input(‘请输入你的用户名:’),
‘password’:input(‘请输入你的密码:’),
‘appid’:’excater’
}
login_sucess = session.post(login_url,data=data_user)

print(login_sucess.text)

if login\_sucess.json()\['result\_code'\] == 0:
    print('2.用户名和密码校验成功!')
    tk\_url = 'https://kyfw.12306.cn/passport/web/auth/uamtk'
    tk\_url\_post =session.post(tk\_url,data={'appid': 'excater'})
    if tk\_url\_post.json()\['result\_code'\] == 0:
        print("3.tk效验成功")
        check\_tk\_url = 'https://exservice.12306.cn/excater/uamauthclient'
        check\_tk\_post = session.post(check\_tk\_url,data={'tk':tk\_url\_post.json()\['newapptk'\]})
        print(check\_tk\_post.text)