selenium日期控件不能直接输入的两种处理方式
2020-11-17 本文已影响0人
阿登20
第一种直接用js
- js先定位到元素
- 修改readOnly = false
- 最后修改值
下面已经12306为案例
image.pngfrom selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from time import sleep
with webdriver.Chrome() as driver:
driver.maximize_window()
driver.get("https://www.12306.cn/index/")
sleep(2)
# ele = driver.find_element_by_xpath('//input[@id="train_date"]')
js = """
var date = document.getElementById("train_date");
date.readOnly = false;
date.value = arguments[0];
"""
driver.execute_script(js, "2020-11-24")
sleep(6)
第 2种
用js将readonly属性去掉删除,driver.execute_script("document.getElementById('date').removeAttribute('readonly')")。这样selenium就可以直接在文本框里输入日期
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from time import sleep
with webdriver.Chrome() as driver:
driver.maximize_window()
driver.get("https://www.12306.cn/index/")
ele = driver.find_element_by_xpath('//input[@id="train_date"]')
driver.execute_script("arguments[0].removeAttribute('readonly');", ele)
# js = """
# var date = document.getElementById('train_date').removeAttribute('readonly');
# """
# driver.execute_script(js)
ele.click() # 先点击,清空后赋值。
ele.clear()
sleep(2)
ele.send_keys("2020-11-24")
sleep(4)
# 下面的操作是将日期控件的小弹框隐藏掉。
js = """
var a = document.getElementsByClassName("cal-wrap")[0].style
a.display = "None"
"""
driver.execute_script(js)
driver.find_element_by_id("search_one").click()
sleep(3)