#!/usr/bin/python2.7 # -*- coding:utf-8 -*- """ 12306自动登录: - 先校验验证码 - 再校验用户名密码 """ import ssl import json import urllib import urllib2 import cookielib # 用来保存cookie c = cookielib.LWPCookieJar() # 存储cookie的对象 cookie = urllib2.HTTPCookieProcessor(c) opener = urllib2.build_opener(cookie) urllib2.install_opener(opener) # 跳过证书验证 ssl._create_default_https_context = ssl._create_unverified_context headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' } # 下载验证码图片 def getCode(): req = urllib2.Request('https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.5074854291360469') req.headers = headers # codeFile = urllib2.urlopen(req).read() codeFile = opener.open(req).read() with open('code.png','wb') as fw: fw.write(codeFile) def login(): """ - 校验验证码 - 没携带cookie: {"result_message":"验证码校验失败,信息为空","result_code":"8"} - 携带cookie但点错了: {"result_message":"验证码校验失败","result_code":"5"} - 携带cookie并且点击正确: {"result_message":"验证码校验成功","result_code":"4"} - 停留时间过长: {"result_message":"验证码已经过期","result_code":"7"} - 校验用户名密码: - 密码输入错误: {"result_message":"密码输入错误。如果输错次数超过4次,用户将被锁定。","result_code":1} - 用户不存在: {"result_message":"登录名不存在。","result_code":1} - 密码输入正确: {"result_message":"登录成功","result_code":0,"uamtk":"tWDQtPie_z22IWMknmFOymUpDRzvLE4CfzREJBzS9NwrwL2L0"} :return: """ getCode() # 坐标型验证码:选几个就有几对(x,y)值;坐标原点在左上角 code = raw_input('请输入验证码>>> ') # POST请求 form_data = { 'answer': code, 'login_site': 'E', 'rand': 'sjrand', } code_url = 'https://kyfw.12306.cn/passport/captcha/captcha-check' form_str = urllib.urlencode(form_data) # 把字典转换成查询字符串,这个方法在urllib2 里是没有的 req = urllib2.Request(code_url) # rsp.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36') req.headers = headers # html = urllib2.urlopen(req,data=form_str).read() # url 或者 对象 html = opener.open(req,data=form_str).read() # url 或者 对象 print html # {"result_message":"验证码校验失败,信息为空","result_code":"8"} code_ret = json.loads(html) if '4' == code_ret['result_code']: print "验证码校验成功,进行校验用户名密码..." req_login = urllib2.Request('https://kyfw.12306.cn/passport/web/login') req_login.headers = headers login_data_dict = { 'username':'xxxxxx', 'password':'123456789', 'appid':'otn', } login_data_str = urllib.urlencode(login_data_dict) login_html = urllib2.urlopen(req_login,data=login_data_str).read() print login_html else: print "验证码校验失败!!!" if __name__ == '__main__': login()