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

Python Selenium加载本地HTML代码时遇JavaScript语法错误及页面加载失败问题求助

解决Selenium加载本地HTML内容的两个常见问题

问题1:document.write注入HTML时的语法错误

你碰到的missing ) after argument list错误,核心原因是直接用字符串格式化把HTML内容嵌入JS代码时,HTML里的引号、换行或特殊字符会直接破坏JS的语法结构。哪怕用json.dumps处理,也没法完全避免这种拼接带来的冲突。

正确的思路是把HTML内容作为参数传递给execute_script,让Selenium自动帮你处理转义逻辑,而非手动拼接JS字符串。修正后的代码如下:

from selenium import webdriver

with open("user1.html") as html_file:
    driver = webdriver.Chrome()
    html_content = html_file.read()
    # 将html_content作为参数传入JS脚本,彻底规避引号冲突问题
    driver.execute_script('document.write(arguments[0])', html_content)

这样不管你的HTML里有什么特殊字符,Selenium都会自动完成转义,不会再出现语法错误。


问题2:data:text/html加载后页面为空

用data:text/html协议时,直接拼接HTML内容会因为**未编码的特殊字符(比如逗号、空格、HTML标签里的引号)**破坏URL结构,导致浏览器无法正确解析内容,最终输出空页面。

解决办法是对HTML内容做URL编码,用Python自带的urllib.parse.quote处理即可:

from selenium import webdriver
from urllib.parse import quote

with open("user1.html") as html_file:
    driver = webdriver.Chrome()
    html_content = html_file.read()
    # 对HTML内容进行URL编码后再拼接成合法的data URL
    encoded_html = quote(html_content)
    driver.get(f"data:text/html;charset=utf-8,{encoded_html}")
print(driver.page_source)

现在浏览器能正确解析完整的HTML内容,driver.page_source也会输出正常的页面结构了。


内容的提问来源于stack exchange,提问作者swor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 03:22:38