python+selenium实现12306模拟火车票的查询及预订:
线性代码实现流程,完整代码如下:
# coding = utf-8
from datetime import date, timedelta
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
# 以下为定义函数部分,其目的是返回今天后的第n天后的日期,格式为“2022-03-28”
def date_n(n):
return str((date.today() + timedelta(days=int(n))).strftime('%Y-%m-%d'))
# 以下变量用于定义出发城市和到达城市
from_station, to_station = '成都', '重庆'
# 以下变量为tomorrow变量
tomorrow = date_n(1)
print(tomorrow)
# 打开chrome浏览器
driver = webdriver.Chrome()
# 设置浏览器最大化
driver.maximize_window()
# 打开携程网火车票查询页面
driver.get('https://www.12306.cn/index/')
# 定位出发城市和到达城市的页面元素
# 输入出发城市
driver.find_element(By.XPATH, '//input[@id="fromStationText"]').click()
driver.find_element(By.XPATH, '//input[@id="fromStationText"]').send_keys(from_station)
driver.find_element(By.XPATH, '//div[@id="citem_2"]').click()
# 输入到达城市
driver.find_element(By.XPATH, '//input[@id="toStationText"]').click()
driver.find_element(By.XPATH, '//input[@id="toStationText"]').send_keys(to_station)
driver.find_element(By.XPATH, '//div[@id="citem_1"]').click()
sleep(2)
# 输入出发时间
driver.find_element(By.XPATH, '//input[@id="train_date"]').clear()
driver.find_element(By.XPATH, '//input[@id="train_date"]').send_keys(tomorrow)
sleep(2)
# 点击查询
driver.find_element(By.XPATH, '//a[@id="search_one"]').click()
sleep(2)
# 切换到新窗口
driver.switch_to.window(driver.window_handles[1])
# 点击D2244车次的预订
# driver.find_element(By.XPATH, '//a[@][1]').click()
driver.find_element(By.XPATH, '//tr[starts-with(@id,"ticket_76000D22440N_01_06")]/td/a').click()
sleep(2)
'''账号登录'''
# 输入用户名
driver.find_element(By.ID, 'J-userName').send_keys('qaws12342')
# 输入密码
driver.find_element(By.ID, 'J-password').send_keys('qwedsa123')
# 关闭浏览器
driver.quit()



