JS操作编辑12306地址日期输入框
有些日期的输入框为只读模式readonly,只能进行选择,无法进行输入,
一、可以通过js语句来修改输入框数据
二、通过JS来修改出发地以及到达地 先定位到,查看输入地址和没输入地址的区别,第二图可见 第一个、北京对应的就是 BJP 第二行的text 只负责页面的显示
三、通过JS修改两处的信息,达到输入的目的 下图的 a 只是负责在页面显示城市名称,没有多大意义,实际查询是以 b 传入的 BJP
代码如下:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # 启动谷歌浏览器 driver = webdriver.Chrome() # 最大化浏览器 driver.maximize_window() # 打开12306 driver.get("https://www.12306.cn/index/") time.sleep(2) # =========================================================================== # 出发地 """ BJP:北京, SHH:上海, TJP:天津, CQW:重庆, CSQ:长沙, CCT:长春 value="BJP" """ ele = driver.find_element_by_id('fromStationText') region = '上海' abbreviation = 'SHH' js = f""" var a = document.getElementById("fromStationText") a.value = "{region}"; var b = document.getElementById("fromStation") b.value = "{abbreviation}"; """ driver.execute_script(js, ele) # =========================================================================== # 到达地 ele = driver.find_element_by_id('toStationText') region = '长春' abbreviation = 'CCT' js = f""" var a = document.getElementById("toStationText") a.value = "{region}"; var b = document.getElementById("toStation") b.value = "{abbreviation}"; """ driver.execute_script(js, ele) # =========================================================================== # 修改时间 ele = driver.find_element_by_id('train_date') cur_time = time.strftime("%Y-%m-%d") js = f""" var a = arguments[0] a.readOnly = false; a.value = "{cur_time}"; """ driver.execute_script(js, ele) # =========================================================================== # 点击 查询 loc = (By.XPATH, '//a[@id="search_one"]') WebDriverWait(driver, 20).until(EC.visibility_of_element_located(loc)) driver.find_element(*loc).click() # 关闭所有窗口 driver.quit()