Using Python crawlers to simulate 12306 login methods

Source: Internet
Author: User
Tried for a long time to log on always show: System busy, please refresh,,, too tortured people, engaged for a half a day to think is the question of the request head ....

Verification code or to manually identify the diagram.

#!/bin/env python#-*-coding=utf-8-*-import sslimport sysimport urllib2import randomimport httplibimport jsonfrom Cooki Elib import lwpcookiejarimport urllibimport reimport getpass Reload (SYS) sys.setdefaultencoding (' UTF8 ') Cookiejar = Lwpcookiejar () Cookiesuppor = Urllib2. Httpcookieprocessor (cookiejar) opener = Urllib2.build_opener (Cookiesuppor, Urllib2. HttpHandler) Urllib2.install_opener (opener) Ssl._create_default_https_context = Ssl._create_unverified_ contextcodeimg = ' https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&%s '%    Random.random () Baner = "" "################################## 12306 Login script, author Mr Rjl Python version: 2.7, for Linux Captcha Input method:    Input problem corresponding to the picture number, 1-8; Multiple separated by ', '. such as: 1,2,3################################## "" "Def get (URL): try:request = Urllib2. Request (Url=url) # req.add_header (' user-agent ', ' mozilla/5.0 (X11; Fedora; Linux x86_64; rv:52.0) gecko/20100101 firefox/52.0 ') request.add_header ("Content-type", "application/x-www-form-urlencoded;                           Charset=utf-8 ") request.add_header (' X-requested-with ', ' XMLHttpRequest ') request.add_header (' User-Agent ', ' mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.154 SAFARI/5 37.36 ') request.add_header (' Referer ', ' Https://kyfw.12306.cn/otn/login/init ') request.add_header (' Accept ', ' */* ') result = Urllib2.urlopen (request). Read () Assert isinstance (result, object) return result exc EPT Httplib.error as E:print e pass except Urllib2. Urlerror as E:print e pass except Urllib2. Httpbasicauthhandler, Urllib2. Httperror:print ' ERROR ' Pass def Post (URL, data): Try:request = Urllib2. Request (Url=url, Data=urllib.urlencode (data)) # Req.add_header (' user-agent ', ' mozilla/5.0 (X11; Fedora; Linux x86_64; rv:52.0) gecko/20100101 firefox/52.0 ') # request = Urllib2.  Request (Ajax_url, Urllib.urlencode (DC))      Request.add_header ("Content-type", "application/x-www-form-urlencoded;                           Charset=utf-8 ") request.add_header (' X-requested-with ', ' XMLHttpRequest ') request.add_header (' User-Agent ', ' mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.154 SAFARI/5 37.36 ') request.add_header (' Referer ', ' Https://kyfw.12306.cn/otn/login/init ') request.add_header (' Accept ', '        */* ') # request.add_header (' accept-encoding ', ' gzip, deflate ') result = Urllib2.urlopen (request). Read () return result except Httplib.error as E:return e except Urllib2. Urlerror as E:return e except Urllib2. Httpbasicauthhandler, Urllib2. Httperror:return ' ERROR ' def COOKIETP (): Stoidinput ("Get Cookie") Url = "Https://kyfw.12306.cn/otn/login/init "Get (URL) for index, C in enumerate (Cookiejar): Stoidinput (c) def getimg (): Stoidinput (" Download Captcha ... ") re    Sult = Get (codeimg) Try:    If open ('/tmp/tkcode ', ' WB '). Write (Result): Import OS Os.system ("Oeg/tmp/tkcode &")    Else:return False except OSError as E:print e pass def stoidinput (text): "" "Normal information output :p Aram Text:: Return: "" "Print" \033[34m[*]\033[0m%s "% text def errorinput (text):" "" error message output: Param text:: return: "" "Print" \033[32m[!] \033[0m%s "% text return False def codexy ():" "" "Get Captcha: Return:str" "" Ofset = Raw_input ("[*] Please Enter the verification code: ") select = Ofset.split (', ') global randcode post = [] offsetsx = 0 # The left value of the selected answer is obtained by clicking the midpoint of the 8 small image in the browser, so Basically no problem offsetsy = 0 # The top value of the selected answer for Ofset in select:if ofset = = ' 1 ': Offsetsy =            FSETSX = elif Ofset = = ' 2 ': Offsetsy = OFFSETSX = 3 "elif Ofset = =": Offsetsy = OFFSETSX = 184 elif Ofset = = ' 4 ': Offsetsy =OFFSETSX = elif Ofset = = ' 5 ': Offsetsy = OFFSETSX = 117 Elif OFSE            t = = ' 6 ': Offsetsy = offsetsx = Offsetsy elif Ofset = = ' 7 ': = 114 OFFSETSX = 181 elif Ofset = = ' 8 ': Offsetsy = 111 OFFSETSX = 252 Else:pa SS Post.append (OFFSETSX) post.append (offsetsy) Randcode = str (POST). Replace ('] ', '). replace (' [', '). Rep Lace ("'", ""). Replace (",") def login (user, passwd): Randurl = ' Https://kyfw.12306.cn/otn/passcodeNew/checkRandCode Ansyn ' LogURL = ' https://kyfw.12306.cn/otn/login/loginAysnSuggest ' sURL = ' https://kyfw.12306.cn/otn/login/userLogin ' Geturl = ' https://kyfw.12306.cn/otn/index/initMy12306 ' Randdata = {"Randcode": Randcode, "Rand": "s Jrand "} logdata = {" Loginuserdto.user_name ": User," Userdto.password ": passwd," Randcode ": Ra Ndcode} ldata = {        "_json_att": None} fresult = Json.loads (Post (Randurl, Randdata), encoding= ' UTF8 ') Checkcode = fresult[' d        ATA ' [' msg '] if Checkcode = = ' FALSE ': Errorinput ("Verification code is incorrect, please retry") Else:stoidinput ("Verification code passed, start login:") Try:tresult = Json.loads (Post (LogURL, Logdata), encoding= ' UTF8 ') if tresult[' data '].__len__ () = = 0                : Errorinput ("Login failed:%s"% tresult[' messages '][0]) else:stoidinput ("Login succeeded") Sult = Post (sURL, Ldata) GetUserInfo () except ValueError as E:errorinput (e) d EF GetUserInfo (): "" "After successful login, display user name: return:" "" "url = ' https://kyfw.12306.cn/otn/modifyUser/initQueryUserInf O ' data = dict (_json_att=none) result = Post (URL, data) UserInfo = result name = R ' <input name= "UserDTO.log Inuserdto.user_name "style=" Display:none; "type=" Text "value=" (\s+) "/>" Try:stoidinput ("Welcome%s login"% re.sear CH (name, result). Group (1)) except Attributeerror:pass def main (): User = Raw_input ("[+] username (username/email/Phone):") passwd = GETPASS.GETPA    SS ("[+] Password:") if user = = ' or passwd = = ': Errorinput ("username or password cannot be empty!") ELSE:COOKIETP () getimg () codexy () login (user, passwd) def logout (): url = ' https://kyfw.123 06.cn/otn/login/loginout ' result = Get (URL) if Result:stoidinput ("exited") Else:errorinput ("Exit failed") I F __name__ = = "__main__": Print Baner Main () logout ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.