在做web自动化过程,有时会遇到文本框为只读状态,无法手动输入值,这时就需要使用js,将其readonly属性设置为false,再进行send_keys操作。
以下代码以12306购票网站为例,首先在浏览器控制台中调试js,查看日期框属性,通过修改只读属性后,再手动赋值,通过以下几行代码,可以看到已经修改了日期框的值:
那么,转换成python代码,如何实现呢?
以下代码中实现了手动修改出发地、目的地和出发日期的功能:
# -*- coding: utf-8 -*- # @Time : 2020/3/17 14:33 # @Author : benben # @File : js_12306.py 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() driver.get("https://www.12306.cn/index/") # 查找出发地 start_text = (By.XPATH, '//input[@id="fromStationText"]') start = (By.XPATH, '//input[@id="fromStation"]') st_ele = driver.find_element(*start_text) s_ele = driver.find_element(*start) # 修改出发地 WebDriverWait(driver, 10).until(EC.visibility_of_element_located(start_text)) time.sleep(3) driver.execute_script('var st=arguments[0];var s=arguments[1];st.value ="北京";s.value="BJP"', st_ele, s_ele) # 查找目的地 to_text = (By.XPATH, '//input[@id="toStationText"]') to = (By.XPATH, '//input[@id="toStation"]') to_ele = driver.find_element(*to_text) t_ele = driver.find_element(*to) # 修改目的地 WebDriverWait(driver, 10).until(EC.visibility_of_element_located(to_text)) driver.execute_script('var tx=arguments[0]; to=arguments[1];tx.value="上海";to.value="SHH"', to_ele, t_ele) # 查找日期框 loc = (By.XPATH, '//input[@id="train_date"]') element = driver.find_element(*loc) # 修改日期框中的 readOnly 属性 d_date = time.strftime("%Y-%m-%d", time.localtime()) driver.execute_script("var a=arguments[0];a.readOnly = false;a.value=arguments[1];", element, d_date) # 点击查询按钮 driver.find_element(By.XPATH, '//a[@id="search_one"]').click() time.sleep(3) driver.quit()