Python Selenium执行JavaScript脚本的同步与异步方法详解

江屿
江屿
发布时间:2026-10-14| 4人浏览过
原创

本文介绍Python Selenium中执行JavaScript脚本的两种核心方法:同步execute_script与异步execute_async_script。通过弹出提示框、获取页面标题、格式化元素及页面滚动等实际代码示例,详细演示了如何在自动化测试中调用JS脚本,涵盖同步执行逻辑及异步执行的注释说明,帮助开发者掌握Selenium与JS交互的关键技巧。

Selenium执行JavaScript脚本的两种方法

WebDriver提供了两种用于执行JavaScript脚本的方法。

第一种是同步执行方式,对应的方法名为execute_script。

第二种是异步执行方式,对应的方法名为execute_async_script。

代码实现:同步与异步执行示例


from selenium import webdriver
from time import sleep
class TestScriptss(object):
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.get(http://www.baidu.com) 
    #执行js提示框,并点确定
    def test_scripts(self):
        self.driver.execute_script("alert('test')")
        sleep(2)
        self.driver.switch_to.alert.accept()
        self.driver.quit() 
    #执行脚本获取当前页面标题
    def test_scripts(self):
        js = "return document.title"
        title = self.driver.execute_script(js)
        print(title)
        sleep(2)
        self.driver.quit()
    #格式化文本框
    def test_format(self):
        js = 'var q = document.getElementById("kw"); q.style.border="10px solid red"'
        self.driver.execute_script(js)
        sleep(5)
        self.driver.quit()
     #通过脚本实现页面滚动
    def test_scroll(self):
        self.driver.find_element_by_id('kw').send_keys('selenium test')
        self.driver.find_element_by_id('su').click()
        sleep(2)
        #搜索结果页面滚动
        js = 'window.scrollTo(0, document.body.scrollHeight)'
        # 同步执行
        self.driver.execute_script(js)
        #异步执行
        # self.driver.execute_async_script(js)
        sleep(2)
        self.driver.quit()

上述内容参考自极客时间课程关于Selenium自动化测试的学习总结。

以上即为Python自动化测试中利用Selenium执行JavaScript脚本的完整实现示例,更多关于Selenium测试框架的详细资料,敬请持续关注本站发布的其他相关文章!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。