[Python] 纯文本查看 复制代码#_*_coding:utf-8_*_
import urllib2,urllib
import ssl
import cookielib
import simplejson
import img
import re
from youjian import send
from station import station_names
stationDict={}
for i in station_names.split('@')[1:]:
stationList=i.split('|')
stationDict[stationList[1]]=stationList[2]
c=cookielib.LWPCookieJar()
cookie=urllib2.HTTPCookieProcessor(c)
opener=urllib2.build_opener(cookie)
urllib2.install_opener(opener)
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',
'Referer':'https://kyfw.12306.cn/otn/resources/login.html'
}
ssl._create_default_https_context=ssl._create_unverified_context
#v出发时间
train_date='2019-01-25'
#起始站
fromStation='深圳'
from_station=stationDict[fromStation]
#终点站
toStation='武汉'
to_station=stationDict[toStation]
#登陆操作
def login():
req=urllib2.Request(
'https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand'
)
req.headers
imgCode=opener.open(req).read()
with open('code.png','wb') as fn:
fn.write(imgCode)
req=urllib2.Request(
'https://kyfw.12306.cn/passport/captcha/captcha-check'
)
req.headers
#code=img.code()
code=raw_input('请输入验证码位置:')
date={
'callback':'jQuery1910948054855148424_1546424454404',
'answer':code,
'rand':'sjrand',
'login_site':'E',
'_':'1546424454425'
}
date=urllib.urlencode(date)
html=opener.open(req,date).read()
req=urllib2.Request(
'https://kyfw.12306.cn/passport/web/login'
)
req.headers
data={
'username':'账号',#12306账号密码
'password':'密码',
'appid':'otn',
}
data = urllib.urlencode(data)
html = opener.open(req, data).read()
result=simplejson.loads(html)
if result['result_code']==0:
print '登陆成功'
#登陆成功后的第一次访问
req = urllib2.Request(
'https://kyfw.12306.cn/passport/web/auth/uamtk'
)
data = {
'appid':'otn'
}
data = urllib.urlencode(data)
req.headers = headers
html = opener.open(req,data=data).read()
result=simplejson.loads(html)
tk=result['newapptk']
# ?第二次访问
req = urllib2.Request(
'https://kyfw.12306.cn/otn/uamauthclient'
)
data = {
'tk':tk
}
data = urllib.urlencode(data)
req.headers = headers
html = opener.open(req,data=data).read()
#查询是否登录成功
'''req = urllib2.Request(
'https://kyfw.12306.cn/otn/index/initMy12306Api'
)
req.headers=headers
html = opener.open(req).read()
print html
return True'''
return True
print '登陆失败,正在重新登录...'