[Python] selenium project actual combat: get the number of second-class seats with tickets for a specific time period from the 12306 website

1. Project background

Tool: python+pycharm+selenium
12306 Website: https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc
Departure: Nanjing
Destination: Shanghai
Departure date: The next day of the current date
Departure time: 06 :00–12:00
Purpose: Print all trains with second-class seats

2. Page search

1. Query conditions

insert image description here

2. Locate elements with second-class seats

insert image description here
Elements with class=yes under the fourth td tag under the id="queryLeftTable" tag, xpath://*[@id="queryLeftTable"]//td[4][@class="yes"]

3. Locate the train number information with second-class seats

insert image description here
Located in the a tag under the first td tag under the upper level tr tag of the element in step 2, xpath://*[@id="queryLeftTable"]//td[4][@class="yes"]/../td[1]//a

4. Ctrl+F checks the number of trains searched by xpath

insert image description here
The search is successful, and the number of trains with second-class seats is 30.

3. Code implementation

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc")
# 需点击出发地输入框再进行输入
ele = driver.find_element(By.ID,"fromStationText")
ele.click()
# 输入出发地(需要按回车键确定)
ele.send_keys("南京\n")

# 需点击目的地输入框再进行输入
ele1 = driver.find_element(By.ID,"toStationText")
ele1.click()
# 输入目的地(需要按回车键确定)
ele1.send_keys("上海\n")

# 选择发车时段
select = Select(driver.find_element(By.ID,"cc_start_time"))
select.select_by_visible_text("06:00--12:00")

# 选择发车时间-当前日期第二天
driver.find_element(By.XPATH,'//*[@id="date_range"]//li[2]').click()

# 选取二等座有座的车次信息
trains = ele2 = driver.find_elements(By.XPATH,'//*[@id="queryLeftTable"]//td[4][@class="yes"]/../td[1]//a')

# 输出二等座有座的车次数量
print("二等座有座的车次数量为:")
print(len(trains))

# 输出二等座有座的车次
print("二等座有座的车次分别为:")
for train in trains:
    print(train.text)
driver.quit()

The running results are as follows:
insert image description here
the number of trains with second-class seats and the train number information match the search results on the page, and the project is completed.

Guess you like

Origin blog.csdn.net/jylsrnzb/article/details/131751525