selenium執(zhí)行JavaScript腳本

一、前言

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)

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容