Spring Festival to take you home with a python rob ticket!

Unconsciously, the annual Spring Festival rush tickets curtain has been opened, want to quickly grab a ticket to go home? As a programmer, these techniques, you must know.

To give you a faster and more convenient to grab tickets, a variety of software to grab votes should be born, most of these software are payment mechanisms to grab votes.

As a programmer, how to grab a ticket to go home with the technical means? Take a look to grab votes script written in Python.

Taught you rush tickets home for the holiday with Python

Environment Introduction

8.1 Windows
python3.6.1
Firefox plug geckodriver.exe

Steps

Introduction to the module

        from Selenium Import the webdriver       # control the browser 
        from selenium.webdriver.common.keys Import Keys   # for assignment to an element 
        Import Time    # Time Module 
        from selenium.webdriver.support.select Import the Select   # control module dropdown box 
        from selenium.webdriver.common .by Import By    # Looking element module 
        from selenium.webdriver.support.ui Import WebDriverWait   # "shows the wait" module 
        from selenium.webdriver.support Import expected_conditions AS EC  # Wait condition module

 

Landing module

You first need to select the browser used, for example firefox here to download: geckodriver.exe.

Mentioned stations.txt can directly look at this:

Station information:

https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9042

The geckodriver.exe into python.exe the same level directory can (if there is an error in the case under a put down to the same directory with the file firefox.exe, and add environment variables)

        # Can be input, can also be placed directly into the back of the user name, password input box 
        # can use the standard input for batch operations, where an individual operation as an example to grab votes 
        # username = str (the INPUT ( 'Please enter your user name: ')) 
        # password = str (the iNPUT (' Please enter your password: ')) # These two lines can be temporarily ignored 

        browser = webdriver.Firefox ()       # driver firefox browser 
        browser.get ( " HTTPS: / /kyfw.12306.cn/otn/login/init " )     # after you start the browser to access the next link 
        browser.find_element_by_id ( ' username ' ) .clear () 
        browser.find_element_by_id ( ' username ' ) .send_keys ( 'XXXXX')     # XXXXX replace username  
        browser.find_element_by_id ( ' password ' ) .send_keys ( 'XXXXX')     # XXXXX password replaced    
        the time.sleep (10)     # At this time codes own click, there is provided 10-second delay, can set their own 
        the try : 
                browser.find_element_by_id ( ' loginSub ' ) .click ()      # click login operation, the id is the login button 
                # or browser.find_element_by_link_text ( 'login') .click () # name label shows 
        the except : 
                browser.find_element_by_class_name ( ' touclick-bgimg touclick-reload Normal-reload-touclick ' ) .click ()      # the try entry point in the wrong codes will be refreshed here
                the time.sleep (20 is)                      # the second input codes wait 20 seconds before, may set up their own, correct the first input skip 
                browser.find_element_by_id ( ' loginSub ' ) .click ()     # re-enter the PIN clicks landed

 

Jump module

# Python study group 592 539 176 
# The default home page to jump to 
        the time.sleep (2)     # here generally do not need to set the time to wait, use debugging code 
        clickReserve = browser.find_element_by_link_text ( ' ticket booking ' ) .click ()   # Jump to ticket book page, which can be queried ticket 
        the time.sleep (2)         # places of departure and arrival point settings 
        # here is the departure point value time, BJP represent Beijing, change the value value is not loaded on the page, almost no time-consuming, from the page can not see the point of departure and destination 
        # here to crawling content stored in stations.txt, each row represents an address to open the document ctrl + F to find 
        the JSF = ' var a = document.getElementById ( "fromStation"); a.value = "BJP" '     # here to replace the starting address BJP you need, value to the value in the stations.txt crawling, the self view 
        browser.execute_script (jsf)
        JST = 'A document.getElementById = var ( "toStation"); a.value = "LZJ" '    # end, supra method 
        browser.execute_script (JST) 
        JS = " document.getElementById (' train_date ') (Readonly') removeAttribute. ' "     # default when time is selected to read-only, read-only attribute is removed by JS 
        browser.execute_script (JS)     # execute JS statement 
        browser.find_element_by_id ( ' train_date ' ) .clear ()     # time element in default prompted word, you need to empty 
        browser.find_element_by_id ( ' train_date ' ) .send_keys ( ' 2018-02-01 ')    # Accordance with the format of the input required to change the query time 
        Search = browser.find_element_by_id ( ' query_ticket ' ) .click ()     # Click OK when entering information inquiry, the presence of adult tickets and student tickets there, the default is adult ticket, if purchased, execute the following statement on the student ticket office can be : 
        # . browser.find_element_by_id ( 'XXXX') the Click () # id for the class or other self or select, [you can see here] (http://blog.51cto.com/12376665/2052278)

 

Tickets start

Here is click predetermined operation, I am here to just give an example of a method, you can also continue clicking until it succeeds (to avoid poor impact site and the actual time of the countdown time, but I do not know 12306 when fast access to constantly grab votes there is no limit).

  = START_TIME " Thu Jan 04 08:00:00 2018 "     # first set time required to grab votes 
        B = time.mktime (the time.strptime (START_TIME, " % A% B% D% H:% M:% S% the Y " ))         Print (The time.strftime ( " % A% B% D% H:% M:% S% the Y " , time.localtime (B)))   # here is used to debug code can be ignored, does not affect use 
        a = float (b) -time.time ()     # use their own time to set the current time minus the timestamp of 
        the time.sleep (a)     # previous step is derived from the number of seconds to wait for time to grab votes of 
the try :      # here would have been enough to try in part, WebDriverWait been waiting for repeated access mechanism corresponding default test time is 0.5 seconds, are added except precaution
    WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID, " ticket_2400000Z550L " )))    # lookup id predetermined trips required, until, wait 10 seconds total of 10 represents 
    Ticket = browser.find_element_by_xpath ( ' / / TR [@ ID = "ticket_2400000Z550L"] / TD [13 is] / A ' ) .click ()     # clicking a predetermined button the except: 
    browser.find_element_by_id ( ' query_ticket ' ) .click () 
    WebDriverWait (Browser, 10) .until ( EC.presence_of_element_located ((By.ID, " ticket_2400000Z550L " ))) 
    Ticket = browser.find_element_by_xpath ( 'TR // [@ ID = "ticket_2400000Z550L"] / TD [13 is] / A ' ) .click ()
 "" " 
normalPassenger_8 under several digits indicate the account, if the default is 0 from the first start was normalPassenger_0 
"" " WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID, " normalPassenger_8 " ))) 
browser.find_element_by_id ( ' normalPassenger_8 ' ) .click ()    # the account id 8 represents the ninth the Select = S (browser.find_element_by_id ( 'seatType_1')) 
s.select_by_value ( ' 6 ' )     # here to see the value of each type value below 6 represents advanced soft browser.find_element_by_id ( 'submitOrder_id'). the Click () 
WebDriverWait (Browser 10).until(EC.presence_of_element_located((By.ID, " Qr_submit_id " ))) 
browser.find_element_by_link_text ( ' Submit Order ' ) 
browser.find_element_by_id ( ' qr_submit_id ' ) .click () # ---------------------- --------------------------- end seat # 1 # 3 # soft sleeper 4 # 6 # second-class sleeper seat senior O (capital letters) # M # business class seat, Block 9

 

to sum up

The place needs to be replaced:

  • Username Password.

  • value value start location and a destination, check stations.txt modifications.

  • departure time.

  • Their choice of trips xpath path, do not change, you can change the corresponding id.

  • Check the user's location (as long as a user if, by default: normalPassenger_0).

  • Seat category selected, default category has the cheapest ticket species.

The rest are the same as in the test and found no change, prior to use, can test code, test code that is commented out attention submitted orders (there is a single lift restrictions next, it seems only canceled three times a day), the test network speed normal.

Some people say that the execution speed of the browser will be slow indeed for the script can directly identify verification code, there is no interface will be faster, but in fact used for the scheduled start time to finish, the same network, code execution time is to faster than manually operated,

In addition, time can study, prior to the study had a treasure of time, spike a little ahead of time is better than Beijing a few seconds, I feel the country is a slight time difference.

Complete Script Example

# Python study group 592 539 176 
# python3.6.1 the Data #: # 2018-01-03 author: LGC247CG "" " 
Note:
 1 . The script is mainly to provide a realization of ideas, to realize there are many ways you can optimize the place, there are many, trigger mechanism can also set up their own code to compress to a minimum, just to let everyone can understand
 2 . under normal network conditions, without setting a specified time, from click to confirm this code to order basically about one second, so the speed or no problem
 3 . Since people and also check single use substantially the same as the time required, it is desirable that the method is used only for the exchange of technology, do not use as cattle
 4 . in the case where a communication technology, if the verification code implementation will be fully automatic grab votes:
 --1> code there are certain rules and number, you can use the script to get all photos, accompanied by an appropriate label
 --2> pages of text and tags match, then the picture similarity calculation, click on the corresponding picture operation
 --3> Image recognition model training or depth learning algorithm by identifying
 "" "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timefrom selenium.webdriver.support.select import Selectfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()
browser.get("https://kyfw.12306.cn/otn/login/init")
browser.find_element_by_id('username').clear()
browser.find_element_by_id('username').send_keys('xxxxxxx')
browser.find_element_by_id('password').send_keys('xxxxxxx')
time.sleep(10)try:
    browser.find_element_by_id('loginSub').click()except:
    browser.find_element_by_class_name('touclick-bgimg touclick-reload touclick-reload-normal').click()
    time.sleep(15)
    browser.find_element_by_id('loginSub '). click () # page to jump to a predetermined ticket time.sleep (2)
clickReserve = browser.find_element_by_link_text ( 'ticket reservation') .click () # places of departure and arrival locations disposed WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID, "fromStation"))) 
JSF = 'var document.getElementById = A ( "fromStation"); a.value = "the BJP" 'browser.execute_script (JSF) 
JST =' var A = document.getElementById ( "toStation"); a.value = "LZJ" 'Browser. execute_script (JST) 
JS = "document.getElementById ( 'train_date'). removeAttribute ( 'Readonly')" browser.execute_script (JS) 
browser.find_element_by_id ( 'train_date'). Clear () 
browser.find_element_by_id('train_date').send_keys('2018-02-02')
Search browser.find_element_by_id = ( 'query_ticket' ) .click () # to time, I have always felt that the site is calculated and the time to get yourself a difference of about one second, the own test start_time = "Thu Jan 04 10:00:00 2018 " depending on the environment# First set time required to grab votes b = time.mktime (time.strptime (start_time, "% a% b% d% H:% M:% S% Y"))
print (time.strftime ( "% a% b% d% H:% M:% S% Y", time.localtime (b))) # here used to debug code can be ignored, does not affect a = float (b) -time.time () # use their own time to set the current time minus the timestamp time.sleep (a) # the previous step is derived from the number of seconds to wait to grab votes of time browser.find_element_by_id ( ' . query_ticket ') click () # time to first click on query refresh, you can not find elements to prevent the try:  
    WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID, "ticket_2400000Z550L"))) 
    Ticket = browser.find_element_by_xpath ( '// TR [@ ID = "ticket_2400000Z550L"] / TD [13 is] / A ') the Click () the except:. 
    browser.find_element_by_id (' query_ticket ').click()
    WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID, "ticket_250000K8880L"))) 
    Ticket = browser.find_element_by_xpath ( '// TR [@ ID = "ticket_250000K8880L"] / TD [13 is] / a'). the Click () "" " 
normalPassenger_8 account number represents the first of several, if the default is the first from 0 It was a normalPassenger_0 
"" " WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID," normalPassenger_8 "))) 
browser.find_element_by_id ( 'normalPassenger_8').click()
s = Select(browser.find_element_by_id('seatType_1')) 
s.select_by_value ( '. 6') 
browser.find_element_by_id ( 'submitOrder_id'). the Click () 
WebDriverWait (Browser, 10) .until (EC.presence_of_element_located ((By.ID, "qr_submit_id") )) 
browser.find_element_by_link_text ( 'submit Order') # browser.find_element_by_id ( 'qr_submit_id' ). click ()

Guess you like

Origin www.cnblogs.com/chengxyuan/p/12150024.html