12306查票操作,请用javascript实现出发地和目的地的选择,日期处理,并提交查询操作。
1 import time 2 from selenium import webdriver 3 from selenium.webdriver.common.by import By 4 from selenium.webdriver.support.wait import WebDriverWait 5 from selenium.webdriver.support import expected_conditions as EC 6 7 driver = webdriver.Chrome() 8 driver.maximize_window() 9 driver.get("https://www.12306.cn/index/") 10 11 time.sleep(5) 12 13 # 1)找到出发地的操作的元素 14 loc_from = (By.XPATH, '//*[@id="fromStation"]') 15 from_element = driver.find_element(*loc_from) 16 from_station = "SHH" 17 18 loc_from_T = (By.XPATH, '//*[@id="fromStationText"]') 19 from_element_T = driver.find_element(*loc_from_T) 20 from_station_T = "input inp-txt_select" 21 from_station_Value = "上海" 22 23 # driver.execute_script("var a = arguments[0];a.value= arguments[1]; ", from_element, from_station) 24 driver.execute_script("var a = arguments[0];a.value= arguments[1]; var b = arguments[2];b.className= arguments[3];b.value =arguments[4];", 25 from_element,from_station,from_element_T,from_station_T,from_station_Value) 26 27 # 2) 找到目的地的操作的元素 28 loc_to = (By.XPATH, '//*[@id="toStation"]') 29 to_element = driver.find_element(*loc_to) 30 to_station = "GZG" 31 driver.execute_script("var a = arguments[0];a.value= arguments[1];", to_element, to_station) 32 33 loc_to_T = (By.XPATH, '//*[@id="toStationText"]') 34 to_element_T = driver.find_element(*loc_to_T) 35 to_station_T = "input inp-txt_select" 36 to_station_Value = "赣州" 37 driver.execute_script("var b = arguments[0];b.class= arguments[1];b.value = arguments[2];", to_element_T, to_station_T,to_station_Value) 38 39 # 3)找到查询时间的操作的元素 40 loc_time = (By.XPATH, '//*[@id="train_date"]') 41 time_element = driver.find_element(*loc_time) 42 train_date = "2020-04-01" 43 driver.execute_script("var a = arguments[0];a.readOnly=false;a.value= arguments[1];", time_element, train_date) 44 45 # 4)输入完成,找到查询按钮,点击查询 46 loc_find = (By.XPATH, '//*[@id="search_one"]') 47 WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc_find)) 48 driver.find_element(*loc_find).click() 49 50 51 # 5)关闭连接 52 time.sleep(10) 53 driver.quit()