12306登录:
登录=请求(绝大多数情况下是POST)
POST里面有几个信息是必不可少的:
1. 请求url(str)
2. 请求方式(str)
3. 参数(str,bytes),其中bytes一般在上传文件时使用;
验证码校验:
url:https://kyfw.12306.cn/passport/captcha/captcha-check
POST
answer:39,45(是一个坐标x,y)
例:
import urllib2,urllib
import ssl
header={
User-Agent:Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/55.0.2883.87 Safari/537.36
}
ssl._create_default_https_context=ssl._create_unverified_context#代表我相信这个网站没有问题
def login():
req=urllib2.Request(https://kyfw.12306.cn/passport/captcha/captcha-check)
req.headers
html=urllib2.urlopen(req).read()
print html
login()
运行结果:
{“验证码校验失败,信息为空”,“result_code”:8}
修改:
import urllib2,urllib
import ssl
import cookielib
from user import user,pwd
c=cookielib.LWPCookieJar() #生成一个存储cookie的对象
cookie=urllib2.HTTPCookieProcessor(c)
opener=urllib2.bulid_opener(cookie)#把这个存储器绑定到opener对象当中
urllib2.install_opener(opener)
headers={
User-Agent:Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/55.0.2883.87 Safari/537.36
}
ssl._create_default_https_context=ssl._create_unverified_context#代表我相信这个网站没有问题
def login():
req=urllib2.Request(https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.4449741254367776)
#图片地址
req.headers=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=headers
code=raw_input(‘请输入验证码:’)
data={
‘answer’:’code’,
‘login_site’:’E’
‘rand’:’sjrand’
}
data=urllib.urlencode(data)
html=opener.open(req,data).read()
req=urllib2.Request(‘https://kyfw.12306.cn/passport/web/login’)
req.headers=headers
data={
‘username’:user,
‘password’:pwd,
‘appid:’otn’
data=urllib.urlencode(data)
html=opener.open(req,data).read()
print html
login()
运行结果:
{“result_message”:”登录成功”,“result_code”:0,“uamtk”: }
相关资料链接:
https://www.jianshu.com/p/443808d3d2b4