selenium execute_script常用方法汇总

driver.execute_script() 是 Selenium WebDriver 中非常强大且灵活的功能,可以用来执行任意的 JavaScript 代码在浏览器上下文中。以下是一些常用的 execute_script() 方法的例子和用法:

  1. 修改元素的属性和值
python 复制代码
python# 修改输入框的值
driver.execute_script("arguments[0].value = '你好'", element)

修改元素的属性

python 复制代码
driver.execute_script("arguments[0].setAttribute('style', 'background: yellow')", element)
  1. 获取元素的属性或值
python 复制代码
python# 获取元素的值
value = driver.execute_script("return arguments[0].value", element)

获取元素的属性

python 复制代码
attribute = driver.execute_script("return arguments[0].getAttribute('attributeName')", element)
  1. 执行滚动操作
python 复制代码
python# 滚动到页面底部
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
#滚动到特定元素
driver.execute_script("arguments[0].scrollIntoView(true);", element)
  1. 执行点击操作
python 复制代码
python# 点击元素
driver.execute_script("arguments[0].click();", element)
  1. 获取页面内容或元数据
python 复制代码
python# 获取页面的标题

title = driver.execute_script("return document.title;")
# 获取页面的URL
url = driver.execute_script("return document.URL;")
  1. 操作浏览器的导航
python 复制代码
python# 前进到下一个页面
driver.execute_script("window.history.go(1);")
# 返回到上一个页面
driver.execute_script("window.history.go(-1);")
  1. 执行复杂的 JavaScript 代码
python 复制代码
python# 执行一个自定义的 JavaScript 函数
result = driver.execute_script("""
    function customFunction() {
        // 自定义逻辑
        return 'Hello from custom function!';
    }
    return customFunction();
""")
  1. 处理 AJAX 请求或动态内容
python 复制代码
python# 等待 AJAX 请求完成
driver.execute_script("""
    var callback = arguments[arguments.length - 1];
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/some/ajax/request', true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        callback(xhr.responseText);
      }
    };
    xhr.send();
""")
  1. 创建和触发事件
    python# 创建并触发一个事件
python 复制代码
driver.execute_script("""
    var event = new Event('change');
    arguments[0].dispatchEvent(event);
""", element)

这些示例展示了 execute_script() 的多种应用方式,可以用来操作页面元素、获取页面信息、控制浏览器行为等等。利用 JavaScript 的灵活性,几乎可以在浏览器中完成任何操作。

相关推荐
程序员三藏1 天前
selenium测试框架快速搭建
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
不会代码的小测试1 天前
UI自动化-日期插件的选择-可输入不可输入情况
javascript·vue.js·python·selenium·自动化
月明长歌1 天前
个人测试项目:一个可跑、可扩、可复用的 Selenium UI 自动化博客系统全链路测试拆解
selenium·ui·自动化
0思必得02 天前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
不会代码的小测试2 天前
UI自动化-针对验证码登录的系统,通过首次手动登录存储cookie的方式后续访问免登录方法
开发语言·python·selenium
0思必得03 天前
[Web自动化] 数据抓取、解析与存储
运维·前端·爬虫·selenium·自动化·web自动化
0思必得03 天前
[Web自动化] 爬虫之API请求
前端·爬虫·python·selenium·自动化
0思必得03 天前
[Web自动化] 爬虫之网络请求
前端·爬虫·python·selenium·自动化·web自动化
深蓝电商API3 天前
Selenium 与 BeautifulSoup 结合解析页面
爬虫·python·selenium·beautifulsoup
深蓝电商API3 天前
Selenium 绕过 Cloudflare 反爬检测
爬虫·python·selenium