You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的nodriver执行JavaScript?兼询Cloudflare绕过方法

解决方案:Nodriver执行JS/修改元素值 + Cloudflare绕过优化

一、修复Nodriver执行JavaScript的问题

你的代码存在两个核心错误:

  • 调用execute_script的对象错误:nodriver中需要在tab对象上执行脚本,而非driver
  • 缺少异步等待:execute_script是异步方法,必须加await

修正后的完整代码:

import asyncio
import nodriver as uc
from time import sleep
import keyboard

url = "https://example.com/"

async def main():
    # 启动浏览器,添加防检测参数
    driver = await uc.start(
        args=[
            "--disable-blink-features=AutomationControlled",
            "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
        ]
    )
    
    tab = await driver.get(url)
    # 等待页面完全加载(关键,避免脚本执行时元素未渲染)
    await tab.wait_for_load()
    
    while True:
        sleep(0.1)  # 降低CPU占用
        if keyboard.is_pressed('g'):
            # 执行修改页面标题的JS
            await tab.execute_script("document.title = 'New Topic';")
            
            # 示例:修改页面输入框值
            await tab.execute_script("""
                const input = document.querySelector('input[name="username"]');
                if(input) input.value = "modified_username";
            """)
            
            print("脚本执行完成")
            # 避免按键长按重复触发
            while keyboard.is_pressed('g'):
                sleep(0.1)

asyncio.run(main())

二、修改页面元素值的两种可行方式

1. 直接执行JavaScript(推荐)

这种方式兼容性最好,不受元素类型限制:

  • 修改输入框值:
    document.querySelector('input#email').value = "new_user@example.com";
    
  • 修改文本内容:
    document.querySelector('.info-text').textContent = "已修改的文本内容";
    
  • 修改元素属性:
    document.querySelector('button.submit-btn').disabled = false;
    

2. 使用Nodriver元素API(部分场景适用)

先定位元素,再调用API修改,适合简单元素:

# 定位元素
element = await tab.select('input#password')
# 设置值(部分复杂元素可能无效,此时用JS更可靠)
await element.set_value('new_password')

三、Cloudflare绕过优化方案

nodriver本身基于无驱动浏览器模拟,绕过Cloudflare的能力优于传统undetected-chromedriver,可通过以下方式进一步提升成功率:

  • 禁用自动化检测特征:启动时添加--disable-blink-features=AutomationControlled参数,避免被浏览器内置检测机制识别
  • 模拟真实用户UA:设置与真实浏览器一致的User-Agent
  • 添加随机延迟:页面加载、操作之间添加随机延迟,模拟真实用户行为:
    import random
    await asyncio.sleep(random.uniform(1.5, 3.5))
    
  • 非无头模式优先:如果不需要后台运行,尽量使用非无头模式(headless=False),更接近真实用户环境
  • 避免批量操作:不要短时间内连续执行大量点击、输入操作,分步骤加间隔

内容的提问来源于stack exchange,提问作者Mirza Geylani Erişen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:30:09