Selenium执行js脚本

如何使用Selenium来执行Javascript脚本呢

Selenium中提供了一个方法:execute_script 来执行js脚本

return 可以返回js的返回结果

execute_script: arguments来进行传参

示例:
场景一:页面显示的 数据比较多,需要点击底部的对象,我们就需要把鼠标移动到底部,才可以点击对象

document.documentElement.scrollTop=1000 调用documentElement的scrollTop方法来滚动页面

在代码中,还可以返回页面的标题和加载性能数据

['return document.title', 'return JSON.stringify(performance.timing)']

场景二:js处理时间控件

打开12306,修改出发日期为2020-12-30,打印出发日期,关闭网址

查找时间元素,去掉该元素的readonly属性

time_element=document.getElementById('train_date'); time_element.removeAttribute('readonly');

再设置时间控件的value属性
date = '2020-12-31'
self.driver.execute_script(f"document.getElementById('train_date').value='{date}'")

posted @ 2020-08-22 13:50  Hei蛋炒饭  阅读(201)  评论(0编辑  收藏  举报