Python Selenium在部分网站无法调用execute_script()函数问题求助
解决Selenium在rplace.live调用execute_script报错的问题
问题描述
同样的Selenium代码,访问google.com时调用execute_script("console.log('hello')")可正常运行,但访问https://rplace.live时触发JavaScript执行错误。
代码示例
from selenium import webdriver import time from selenium.webdriver.common.by import By service = webdriver.ChromeService(executable_path = 'chromedriver.exe') options = webdriver.ChromeOptions() driver = webdriver.Chrome(service=service) driver.get("https://www.rplace.live") driver.execute_script("console.log('hello')") input("....")
报错信息
Traceback (most recent call last): File "C:\Users\AkaMehmet\Desktop\chromedriver_win32\main - Kopya.py", line 14, in <module> driver.execute_script("console.log('hello')") File "C:\Users\AkaMehmet\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 408, in execute_script return self.execute(command, {"script": script, "args": converted_args})["value"] File "C:\Users\AkaMehmet\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 348, in execute self.error_handler.check_response(response) File "C:\Users\AkaMehmet\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.JavascriptException: Message: javascript error: Function is not defined (Session info: chrome=109.0.5414.168)
原因分析
rplace.live这类网站大概率启用了内容安全策略(CSP),或者对页面的JavaScript执行环境做了沙箱限制,导致Selenium注入的脚本无法访问标准全局函数;也可能是页面未完全加载完成就执行了脚本,JS环境尚未初始化。
解决方案
1. 等待页面完全加载后执行脚本
使用WebDriverWait等待页面核心元素加载完成,确保JS环境初始化完毕:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC service = webdriver.ChromeService(executable_path = 'chromedriver.exe') options = webdriver.ChromeOptions() driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.rplace.live") # 等待body元素出现,最长等待10秒 WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body"))) driver.execute_script("console.log('hello')") input("....")
2. 禁用Chrome的CSP限制
通过ChromeOptions添加参数关闭内容安全策略检查:
from selenium import webdriver import time from selenium.webdriver.common.by import By service = webdriver.ChromeService(executable_path = 'chromedriver.exe') options = webdriver.ChromeOptions() # 添加禁用CSP的参数 options.add_argument("--disable-content-security-policy") driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.rplace.live") driver.execute_script("console.log('hello')") input("....")
3. 改用自执行函数包裹脚本
部分受限环境对直接执行语句有要求,用自执行函数包裹脚本尝试:
driver.execute_script("(function(){ console.log('hello'); })();")
注意事项
- 禁用CSP会降低浏览器的安全性,仅建议在测试环境使用;
- 部分网站存在反爬机制,频繁执行脚本可能会被检测并限制访问。
内容的提问来源于stack exchange,提问作者Mehmet Tok
相关产品推荐
相关产品推荐

