使用selenium直接在当前页面中进行js交互
1.常用的几种操作使用js实现
- selenium执行js,那么js能做的,selenium大部分也能做
- 直接使用js操作页面,能解决很多click()不生效的问题
- 页面滚动到底部、顶部
- 处理富文本、时间控件的输入,获得页面性能数据JSON.stringify(performance.timing)
2.selenium中如何调用js
- execute_script:执行js
- return:可以返回js的返回结果
- execute_script:arguments传参
input_ele = self.driver.execute_script("return document.getElementById('su')") input_ele.click()
3.js处理时间控件
1)大部分时间控件都是readonly属性,自动化用js来操作
2)处理时间控件思路
- 取消日期的readonly属性
- 给value赋值
- 写js代码是实现上叙两点,再webdriver对js进行处理
def test_datetime(self):
self.driver.get("https://www.12306.cn/index/")
time_ele =
self.driver.execute_script("a=document.getElementById('train_date');a.removeAttribute('readonly');a.value='2021-11-04'")
sleep(3)