Selenium提供了两种执行JavaScript脚本的方法:execute_script:同步执行——常用execute_async_script:异步执行应用场景一:时间输入框一些时间输入框控件已经添加了readonly属性,限制控件只读,不可写。那么就不能通过send_keys()直接输入内容了。这种情况的处理方法及步骤:通过JavaScript脚本去掉readonly属性,清空输入框内容以时间格式输入信息fromseleniumimportwebdriverfromtimeimportsleeppedriver=webdriver.Chrome()#打开浏览器驱动。get("https://www.12306.cn/index/")#跳转到测试页面sleep(1)js="document.getElementById('train_date').removeAttribute('readonly')"#写一段JavaScript删除只读属性的语句driver.execute_script(js)#同步执行JavaScript语句element=driver.find_element_by_id("train_date")#定位元素element.clear()#清除内容sleep(1)element.send_keys("2020-08-10")#输入内容sleep(2)driver.quit()#关闭浏览器应用场景二:操作滚动条操作滚动条常用的JavaScript语句:序号JavaScript语句说明1document.documentElement.scrollTop=10002window.sc从最上面移动到第1000个位置rollTo(0,document.body.scrollHeight*0.5)根据高度比例移动到绝对位置(x轴方向,y轴方向)3window.scrollTo(0,1000)移动到绝对坐标位置(x-轴方向,y轴方向)4window。scrollBy(0,-200)相对于当前坐标移动相应的距离(x轴方向,y轴方向)seleniumimportwebdriverfromtimeimportslepdriver=webdriver.Chrome()#打开浏览器driver.get("https://www.douban.com/")#跳转到测试页面sleep(1)js1="document.documentElement.scrollTop=500"#y轴方向移动到距顶部500的位置js2="window.scrollTo(0,document.body.scrollHeight*0.5)"#y轴方向移动到坐标为总高度的50%js3="window.scrollTo(0,1000)"#移动到y轴方向高度为1000的位置js4="window.scrollBy(0,-500)"#向上移动500相对于当前位置driver.execute_script(js1)#执行JavaScript语句sleep(3)driver.execute_script(js2)#执行JavaScript语句sleep(3)driver.execute_script(js3)#执行JavaScript语句sleep(3)driver.execute_script(js4)#执行JavaScript语句sleep(3)driver.quit()#关闭浏览器摘要
