Python implements the 12306 ticket snatching and automatic email sending reminder payment function, python12306

Source: Internet
Author: User

Python implements the 12306 ticket snatching and automatic email sending reminder payment function, python12306

# In front of this article, I have already developed this program. However, the code of the entire program will not be posted because of the scalping and lazy people. This is purely a technical exchange.

Only technical exchanges ,,,,,

Well, after the program ends, you still have to pay manually.

If you don't talk much about it, let's start with the main sections of the technology.

First, let's talk about the theory. First, we need code to implement a browser function. Then the module can basically determine urllib. parse, urllib. request, both packages are URL-related modules, so we can log on to a website, especially a website with a verification code. Can we log on? The answer is correct, but if we use code to implement it, this URL may be requested by the code every time. How does the server know that we are a person, instead of using different browsers?

At this time, cookies are very important. After the cookie is set in the Code, the other server naturally knows that we are a person, and the comparison servers are so differentiated. In python3, the cookie function is encapsulated in the http. cookiejar module. The Code is as follows:

# Coding = UTF-8 # author: Jason # time: 20:00:00 # version: 1.0 import urllib. request as ulimport urllib. parse as uzimport http. cookiejar as cookielibfrom json import loadsc = cookielib. LWPCookieJar () # first store the cookie object as the cookie of cookiejar = ul. HTTPCookieProcessor (c) # converts a cookiejar object to a handleopener = ul. build_opener (cookie) # create a simulated browser and use handle as the parameter ul. install_opener (opener) # installing a global simulated browser means that no matter how you access it, it is a browser operation rather than separately obtaining the verification code and other msg

Now, the initial implementation of our code has been completed, and the next step is to enter the Network Analysis Section.

First you can use google browser or sogou browser (I use sogou), open F12, that is, the developer mode, login 12306 login address https://kyfw.12306.cn/otn/login/init

The second one in the two red circles is the verification code source. In this case, we only need to record the details of the webpage (click in). When writing the code, the urllib. request module in python3 can be opened.

This is the source of the Verification Code. How can we capture the code? First, we can randomly enter the password, click the verification code, and then click log on.

There is another amazing thing. Here is the verification code verification URL. Should we record it? It's easy. You can see it in Headers.

The above is the server verification URL, and the following is what we reply to him, so that 163,121 is actually the coordinates of the verification code that I randomly clicked. As for why it is a coordinate, because it uses the mouse to point an image, then he can only record the coordinates, unless he has made a set of artificial intelligence to verify the image, however, since he played this game a few years ago, artificial intelligence has never started. Naturally, he can only be the most primitive technology.

This means that he verifies the verification code first. Where is the verification code? Naturally, we need to pass the verification code. Then we will enter a correct verification code, write an incorrect password, and log on.

At this point, we can see that, in the same way as the verification code, our response and verification are all in these circles. Do you still remember that there is a number for the code we replied to when the verification code above fails? This is also very important. Let's take a look at what the verification code returned to us.

This time, we can see that the verification code is successful and displayed as 4. OK. Can we just make a conditional judgment?

So how to open a website and send the items we ordered together? Code on

Headers = {'user-agent': 'mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/63.0.3239.84 Safari/537.36 '} # first write a head, indicating that I log on as a browser user rather than a code logon. If no code is written, the default signature of the Code is a programming language identifier, in this way, the other server will easily find that you are a script.
Def get_code (): # Step for obtaining the verification code req = ul. Request ('https: // kyf201712306.cn/passport/captcha/captcha-image? Login_site = E & module = login & rand = sjrand & 000000') req. headers = headers code_file = opener. open (req ). read () # at this time, the browser's open is no longer ul. urlopen, the same as with open (r 'C: \ Users \ Administrator \ Desktop \ 12306 Automatic Ticketing \ code.png ', 'wb') as f: f. write (code_file)

Download the Verification Code directly to the computer at the rear. You only need to open the figure after the coordinates. You can enter the coordinates in a dictionary. {1 :( 45, 45 )} {2 :( 120,45)} {3 :( 1845,120)} {4 :( 255, 45)} {5 :( 120,120)} {6 :( 180,120)} {7 )} {8 :( 255,120 )}

According to the sorting of the verification code, I believe that the reader should know how the order comes from, and then compare the coordinates to understand.

Continue

Def main _ (): get_code () code = input ('input verification code: ') req = ul. request ('https: // kyf201712306.cn/passport/captcha/captcha-check') req. headers = headers data = {'answer': code, 'login _ site': 'E', 'rand': 'sjrand'} data = uz. urlencode (data ). encode () # converts a dictionary to a URL query string, which is str. You need to change it to byts. Html = opener. open (req, data = data ). read (). decode () # The read result is in byts format and converted to 'utf-8 (default) print (html) result = loads (html) if result ['result _ Code'] = '4': print ('verification code pass') rep = ul. request ('https: // kyf201712306.cn/passport/web/login') rep. headers = headers data = {'username': 'Here is your username', 'Password': 'Here is your password', 'appid ': 'otn'} data = uz. urlencode (data ). encode () # see it. This is what you reply to the server html1 = opener. open (rep, data = data ). read (). decode () result1 = loads (html1) if result1 ['result _ Code'] = 0: print ('account password verification pass') else: print (result1 ['result _ message']) else: print ('verification code verification failed, repeat ') if _ name _ =' _ main __': main _()

At this point, we have passed the verification code and password. Are we going to check the tickets later? In this way, we can move the code to the last step.

Ps: it is very important to check the code information. We need to record it, and the information here contains various information and their order, this can be achieved after multiple tests. Here is a reminder.

Find the rule, and then use the split method to completely cut it out. Then, in a loop, we can get the first few elements that we want. Then, we can mark and judge whether the returned value is none, you can continue querying without a ticket until you have a ticket;

If you have a ticket, the following method is the same, and so on. I will not reproduce the code. It is very simple. I will send the URLs that need to be requested for observation.

Query ticket information

url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(train_data,from_station,to_station)
Req = ul. request ('https: // kyf201712306.cn/otn/leftticket/submitorderrequest') # confirm the order information req = ul. request ("https://kyfw.12306.cn/otn/confirmPassenger/initDc") # verify order req = ul. request ('https: // kyf201712306.cn/otn/confirmpassenger/getpassengerdtos') # Prepare excessive req = ul for cross-order placement. request ('https: // kyf201712306.cn/otn/confirmpassenger/checkorderinfo') # Check order information req = ul. request ('https: // kyf201712306.cn/otn/confirmpassenger/getqueueco Unt ') # submit the information to the server and prepare to go to the order step req = ul. request ('https: // kyf201712306.cn/otn/confirmpassenger/confirmsingleforqueue') # enter the order step req = ul. request ('https: // kyf201712306.cn/otn/confirmpassenger/queryorderwaittime? Random = % s & tourFlag = dc & _ json_att = & REPEAT_SUBMIT_TOKEN = % s' % (numb, time. time () # in the order confirmation process, this website is generally accessed twice. I do not know why, numb is one of the information in the previous query ticket and click the reservation to reply to us. It is a bit difficult to find. I have been searching for three days... Of course, it's because you're not careful about it. zreq = ul. Request ("https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue") # The final result receipt, if everything goes well, then the ticket has been booked. I usually print the returned content ''' zreq = ul. request ("https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue") zreq. headers = headers data = {"REPEAT_SUBMIT_TOKEN": "% s" % numb, "_ json_att": "", "orderSequence_no": orderId} data = uz. urlencode (data ). encode () html = opener. open (zreq, data = data ). read (). decode () result = loads (html) print) print (result ['data'] ['submitstatus']) if result ['data'] ['submitstatus'] = True: print ('ticket purchased successfully ') return True else: print ('ticket purchase failed, retry other training') continue ''' detailed information of the final receipt code. You can try it multiple times by yourself, get your reply code to confirm whether the ticket is successfully purchased, because result ['data'] ['submitstatus'] = True is only a confirmation of the order status, which has been changed by me, you can try it multiple times

At last, the ticket reservation was completed only 30 minutes, so I wrote a qq email notification to prevent the ticket from being booked but I was not here.

Qq email notification:

Def email (): # This is the function import smtplib from email that I sent to myself after booking tickets. mime. text import MIMEText import time text = 'the ticket has been snatched for % s. log on to 12306 for payment at a speed. username: % s, password: % s' % (NAME, username, password) msg = MIMEText (text, 'plain ', 'utf-8') msg_From = '2017 *** 16@qq.com 'msg_to = '2017 *** 75@qq.com' # Yes, I have two qq accounts, send one smtpSever = 'smtp .qq.com '# smtp Sever address of the QQ mailbox smtpPort = '000000' # Open Port sqm = 'q ********* eghe '# when you log on to smtp, you must use the authorization code instead of the account for the password in login. User Password msg ['from'] = msg_From msg ['to'] = msg_To msg ['subobject'] = 'python automatic mail-% s' % time. ctime () smtp = smtplib. SMTP_SSL () ''' smtplib connect (connected to the mail server), login (login verification), sendmail (send mail) ''' smtp. connect (smtpSever, smtpPort) smtp. login (msg_From, sqm) smtp. sendmail (msg_From, msg_To, str (msg) # s = smtplib. SMTP ("localhost") # s. send_message (msg) smtp. quit () print ('email sent ~ You can play ') def emailforcode (): # This function is used to prevent the user who has a ticket but the 12306 account has been dropped from the ticket booking reminder. import smtplib from email. mime. text import MIMEText import time text = '% s account offline, speed logon verification 12306' % NAME msg = MIMEText (text, 'plain ', 'utf-8 ') msg_From = '100 * 516@qq.com 'msg_To = '50 * 75@qq.com' smtpSever = 'smtp .qq.com '# smtp Sever address smtpPort = '2016' # Open port sqm = 'qowa ******** ghe '# The authorization code must be used for the password in login when logging on to smtp, instead of the account password msg ['from'] = m Sg_From msg ['to'] = msg_To msg ['subobject'] = 'python automatic mail-% s' % time. ctime () smtp = smtplib. SMTP_SSL () ''' smtplib connect (connected to the mail server), login (login verification), sendmail (send mail) ''' smtp. connect (smtpSever, smtpPort) smtp. login (msg_From, sqm) smtp. sendmail (msg_From, msg_To, str (msg) # s = smtplib. SMTP ("localhost") # s. send_message (msg) smtp. quit () print ('email sent ~ ')

This is all done.

You cannot send complete code (the purpose of this Code is only for technical communication to prevent lazy people from messing around with code), but I believe that all the friends in development can start with logic and work as long as they are willing to do it on their own, you can work it out on your own. After all, this is what I did. I always believe that as long as I want to learn, I will learn what I want to do.

Summary

The above section describes how to implement the 12306 ticket snatching and automatic email sending reminder payment function in python. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.