Teach you how to use python to get a ticket to go home for the New Year (simple code), python to go home for the New Year
First, let's take a look at how to quickly view the remaining train tickets?
When you want to query the train ticket information, do you still go to the 12306 official website? Or open the APP on your phone? Next, let's use Python to write a line-of-command train ticket viewer. You only need to type a line of command on the command line to get the desired train ticket information! If you have just mastered the basics of Python, this will be a good little exercise.
Interface Design
An application is ultimately intended for use, even if it is for your own use. So first, you should think about how you want to use it? Let's give a name to this small application first. Now that we can query the ticket information, we can call it tickets. We hope that users can get the desired information as long as they enter the origin site, arrival site, and date. Therefore, tickets should be used as follows:
$ tickets from to date
In addition, there are various types of trains: high-speed trains, bullet trains, express trains, fast trains, and direct trains. We hope to provide options to query only one or more specific trains, we should have the following options:
- -G high-speed trains
- -D EMU
- -T express
- -K fast
- -Z direct
These options should be used in combination. Therefore, our interface should look like this:
$ tickets [-gdtkz] from to date
The interface has been fixed, and the rest is to implement it.
Development Environment
A good practice for writing Python programs is to use virtualenv to create a virtual environment. Our program is developed using Python3. Next we will create a folder named tickets in your working directory to create a virtual environment:
$ virtualenv -p /usr/bin/python3 venv
Run the following command to activate it:
$ . venv/bin/activate
Resolution Parameters
Python has many tools for writing command line applications, such as argparse, docopt, options... Here, we use the simple and easy-to-use tool docopt. We should install it first:
$ pip3 install docopt
Docopt can parse parameters according to the format defined in the document string, in tickets. py:
Run the following program:
$ Python3 tickets. py Shanghai Beijing
The following Parameter Parsing result is obtained:
Get Data
The parameters have been parsed. The following describes how to obtain the data, which is also the most important part. First, open 12306 to go to the ticket remaining query page. If you use chrome, press F12 to open the developer tool, select the Network column, and enter Shanghai to Beijing in the query box, date:. Click query. We found in the debugging tool that the query system actually requested this URL.
Https://kyfw.12306.cn/otn/lcxxcx/query? Purpose_codes = ADULT & queryDate = 2016-07-01 & from_station = SHH & to_station = BJP
The returned data is in Json format! Next, the problem is simple. We only need to construct the request URL and parse the returned Json data. But we found that from_station and to_station in the URL are not Chinese characters, but a code, and users enter Chinese characters. How do we get the code? Open the web page source code to see if there is any discovery.
Aha! Sure enough, we found this link in the web page: https://kyfw.12306.cn/otn/resources/js/framework/station_name.js? Station_version = 1.8955
It may include Chinese names, Pinyin, abbreviations, codes, and other information of all stations. We save tokens as stations.html in the project directory. However, this information is crowded together, and we only want the code information of Chinese names and uppercase letters. What should we do?
BINGO! Regular Expression. Let's write a small script to match and extract the desired information. In parse. py:
We run this script and it will return all stations and their uppercase letters and codes in a dictionary. We will redirect the results to stations. py,
$ python3 parse.py > stations.py
We add the name stations to this dictionary. In the end, the stations. py file is like this:
Now, if you enter the Chinese name of the station, we can directly obtain its letter code from the dictionary:
Everything is ready. Let's request this URL for data! Here we use the requests library and install it first:
$ pip3 install requests
It provides very easy-to-use interfaces,
From the results, we can see that the information related to the ticket needs to be further extracted:
Display result
The data has been obtained, and the rest is to extract the information we need and display it. The prettytable database allows us to format and display data like the MySQL database.
$ pip3 install prettytable
Use it like this:
Next, let's take a look at how to automatically grab:
Author: marvin, Internet practitioner, now lives in Zhangjiang, Shanghai
You can use Python + Splinter to automatically refresh the ticket to get the ticket. (Depending on your own network environment is too powerful, there are good or bad machines)
Splinter is an open-source Web application testing tool developed using Python. It can help you automatically browse the site and interact with it. When executing Splinter, it will automatically open your specified browser, access the specified URL. Then, any simulated behavior you develop will be automatically completed. You just need to sit in front of your computer and watch the various actions on the screen like watching a movie and then collect the results.
Python code snippet for 12306 ticket snatching
Functions for Automatic Logon:
Function for starting ticket purchase
Source code:
#-*-Coding: UTF-8-*-"@ author: liuyw" from splinter. browser import Browserfrom time import sleepimport tracebackimport time, sysclass huoche (object): "" docstring for huoche "driver_name = ''executable_path ='' # user name, password username = u "xxx@qq.com" passwd = u "xxxx" # cookies are worth looking for, the following two are Shanghai, taiyuan South starts = u "% u4E0A % u6D77 % 2 CSHH" ends = u "% u592A % u539F % 2 CTYV" # Time Format 8-01-1-19 dtime = u "2018-01-19" # Train times Select the number of times, and click order = 0 ### passenger name users = [u "xxx ", u "xxx"] # seat xb = u "second seat" pz = u "adult pass" "ticket_url =" https://kyfw.12306.cn/otn/leftTicket/init "login_url =" https://kyfw.12306.cn/otn/login/init "initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" login_url = 'https: // kyf000012306.cn/otn/login/init' def _ init _ (self): self. driver_n Ame = 'chrome 'self.exe cutable_path ='/usr/local/bin/chromedriver 'def login (self): self. driver. visit (self. login_url) self. driver. fill ("loginUserDTO. user_name ", self. username) # sleep (1) self. driver. fill ("userDTO. password ", self. passwd) print u "Wait for the verification code and enter the verification code... "while True: if self. driver. url! = Self. initmy_url: sleep (1) else: break def start (self): self.driver?browser(driver_name=self.driver_name,executable_path=self.exe cutable_path) self. driver. driver. set_window_size (1400,100 0) self. login () # sleep (1) self. driver. visit (self. ticket_url) try: print u "ticket purchase page starts... "# sleep (1) # load the query information self. driver. cookies. add ({"_ jc_save_fromStation": self. starts}) self. driver. cookies. add ({"_ jc_save_toStation ": Self. ends}) self. driver. cookies. add ({"_ jc_save_fromDate": self. dtime}) self. driver. reload () count = 0 if self. order! = 0: while self. driver. url = self. ticket_url: self. driver. find_by_text (u "query "). click () count + = 1 print u "loop click query... % s "% count # sleep (1) try: self. driver. find_by_text (u "Reservation") [self. order-1]. click () Cancel t Exception as e: print e print u "has not started booking" continue else: while self. driver. url = self. ticket_url: self. driver. find_by_text (u "query "). click () count + = 1 print u "loop click query... % s times "% count # sleep (0.8) try: for I in self. driver. find_by_text (u "Reservation"): I. click () sleep (1) failed t Exception as e: print e print u "haven't started booking % s" % count continue print u "Start booking... "# sleep (3) # self. driver. reload () sleep (1) print U' start to select the user... 'for user in self. users: self. driver. find_by_text (user ). last. click () print u "Submit order... "sleep (1) # self. driver. find_by_text (self. pz ). click () # self. driver. find_by_id (''). select (self. pz) # sleep (1) # self. driver. find_by_text (self. xb ). click () # sleep (1) self. driver. find_by_id ('submitorder _ id '). click () # print u "to start seat selection... "# self. driver. find_by_id ('1d '). last. click () # self. driver. find_by_id ('1f '). last. click () sleep (1.5) print u "to confirm seat selection... "self. driver. find_by_id ('qr _ submit_id '). click () failed t Exception as e: print eif _ name _ = '_ main _': huoche = huoche () huoche. start ()
Summary
The above is a small series of experts who teach you how to use python to grab a ticket and go home for the New Year (simple code). I hope it will help you. If you have any questions, please leave a message for me, the editor will reply to you in time!