一、前言
1.selenium能夠執(zhí)行js腳本,這使得selenium擁有更為強大的能力。既然能執(zhí)行js,那么js能做的事情,selenium應該大部分都能做。
2.直接使用js操作頁面,可以解決很多click()不生效的問題
3.頁面滾動到底部、頂部
4.處理富文本、時間控件的輸入等。
二、示例( 修改12306網(wǎng)站的出發(fā)時間 )
# -*- coding:utf-8 -*-
# @File:test_js.py
import time
import allure
from selenium_test.selenium_js.base import Base
class TestJS(Base):
? ? @allure.feature("打開百度,搜索selenium測試,點擊搜索,滾動到底部")
? ? def test_js_scroll(self):
? ? ? ? self.driver.get("https://www.baidu.com/")
? ? ? ? self.driver.find_element_by_id('kw').send_keys('selenium測試')
? ? ? ? element = self.driver.execute_script("return document.getElementById('su')")
? ? ? ? element.click()
? ? ? ? time.sleep(2)
? ? ? ? self.driver.execute_script("document.documentElement.scrollTop=2000")
? ? ? ? time.sleep(2)
? ? ? ? self.driver.find_element_by_xpath('//*[@id="page"]/div/a[10]').click()
? ? ? ? time.sleep(5)
? ? ? ? for code in [" return document.title", "return JSON.stringify(performance.timing)"]:
? ? ? ? ? ? print(self.driver.execute_script(code))
? ? @allure.feature("修改12306網(wǎng)站的出發(fā)時間")
? ? def test_datetime(self):
? ? ? ? self.driver.get("https://www.12306.cn/index/")
? ? ? ? self.driver.execute_script("a=document.getElementById('train_date');a.removeAttribute('readonly');a.value='2020-08-10'")
? ? ? ? time.sleep(5)
? ? ? ? print(self.driver.execute_script('return document.getElementById("train_date").value'))
? ? ? ? time.sleep(3)