代码:
from selenium.webdriver.common.keys import Keys from selenium import webdriver import time,datetime # 显式等待引入相关库 from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait driver = webdriver.Chrome() # driver.implicitly_wait(20) driver.get("https://www.12306.cn/index/") wait = WebDriverWait(driver,20) time.sleep(2) # 构造出发地的js js_from_station = """ var ele_fromStationText = document.getElementById("fromStationText"); ele_fromStationText.value="上海"; var ele_fromStation = document.getElementById("fromStation"); ele_fromStation.value="SHH"; """ # 执行js,修改出发地的值 driver.execute_script(js_from_station) time.sleep(2) # 构造到达地的js js_toStation = """ var ele_toStationText = document.getElementById("toStationText"); ele_toStationText.value = "北京" var ele_to_station = document.getElementById("toStation"); ele_to_station.value="BJP"; """ # 执行js,修改到达地的值 driver.execute_script(js_toStation) time.sleep(2) # 构造js,来修改出发日期。 js_pha = """ var ele_datatime = document.getElementById("train_date"); ele_datatime.readOnly=false; ele_datatime.value="2019-10-01" """ # 执行js,修改出发日期 driver.execute_script(js_pha) # 点击“查询”按钮 loc = (By.XPATH,'//a[@id="search_one"]') wait.until(EC.visibility_of_element_located(loc)) element = driver.find_element(*loc).click()