#-*-coding:utf-8 -*-
import urllib2
import urllib
# 验证码登录同步
import cookielib
import ssl
#证书验证
ssl._create_default_https_context = ssl._create_unverified_context
# 请求验证码图片
c=cookielib.LWPCookieJar()#生成一个储存cookie的对象
cookie=urllib2.HTTPCookieProcessor(c)#绑定
opener=urllib2.build_opener(cookie)
urllib2.install_opener(opener)
# opener绑定,用opener.open请求,自带cookie,实现验证码与登陆同步req=urllib2.Request("https://kyfw.12306.cn/passport/captcha/""captcha-image?login_site=E&module=""login&rand=sjrand&0.3835166812770916")
codeing=opener.open(req).read()#opener
fn=open('code/code.png','wb')
#保存到本地
fn.write(codeing)
fn.close()req=urllib2.Request('https://kyfw.12306.cn/passport''/captcha/captcha-check')
code=raw_input(">>")
data={
"answer":code,
"login_site":"E",
"rand":"sjrand",
}
data=urllib.urlencode(data)#把字典类型转变为查询字符串
html=opener.open(req,data=data).read()
print html#登录
req=urllib2.Request('https://kyfw.12306.cn/passport''/web/login')data={'username':'abcdert','password':'123456','appid':'otn',
}
data=urllib.urlencode(data)
html=opener.open(req,data=data).read()
print html
输入验证码位置,账号密码改为自己的就可以了。
>>258,44
{"result_message":"验证码校验成功","result_code":"4"}
{"result_message":"密码输入错误。如果输错次数超过4次,用户将被锁定。","result_code":1}