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

如何修复Python Selenium脚本中的innerHTML赋值错误

Gmail更新后Selenium脚本设置innerHTML报错(TrustedHTML要求)

问题背景

Python+Selenium开发的Gmail发送脚本此前运行正常,Gmail更新后出现JavaScript错误,无法将HTML模板内容插入邮件正文区域。

错误信息

selenium.common.exceptions.JavascriptException: Message: javascript error: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment.
  (Session info: chrome=122.0.6261.111)

完整错误栈:

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\New folder\gmailsender.py", line 101, in <module>
    sb.driver.execute_script(f'document.querySelector(\'div[role=&quot;textbox&quot;]\').innerHTML = `{body_content}`;')
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 407, in execute_script
    return self.execute(command, {"script": script, "args": converted_args})["value"]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 347, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Administrator\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: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment.
  (Session info: chrome=122.0.6261.111)
Stacktrace:
        GetHandleVerifier [0x00007FF72267AD22+56930]
        (No symbol) [0x00007FF7225EF622]
        (No symbol) [0x00007FF7224A42E5]
        (No symbol) [0x00007FF7224A9261]
        (No symbol) [0x00007FF7224AB9FD]
        (No symbol) [0x00007FF722528E57]
        (No symbol) [0x00007FF72250BC9A]
        (No symbol) [0x00007FF7225281E2]
        (No symbol) [0x00007FF72250BA43]
        (No symbol) [0x00007FF7224DD438]
        (No symbol) [0x00007FF7224DE4D1]
        GetHandleVerifier [0x00007FF7229F6AAD+3709933]
        GetHandleVerifier [0x00007FF722A4FFED+4075821]
        GetHandleVerifier [0x00007FF722A4817F+4043455]
        GetHandleVerifier [0x00007FF722719756+706710]
        (No symbol) [0x00007FF7225FB8FF]
        (No symbol) [0x00007FF7225F6AE4]
        (No symbol) [0x00007FF7225F6C3C]
        (No symbol) [0x00007FF7225E68F4]
        BaseThreadInitThunk [0x00007FF8B4BE4ED0+16]
        RtlUserThreadStart [0x00007FF8B5ACE39B+43]

报错代码行:
sb.driver.execute_script(f'document.querySelector(\'div[role=&quot;textbox&quot;]\').innerHTML = {body_content};')

问题原因

Gmail更新后启用了Trusted Types安全机制,该机制会阻止直接将字符串赋值给innerHTML等风险属性,要求必须使用经过信任的TrustedHTML类型内容,防止XSS攻击。

解决方案

方法1:使用Trusted Types API合法赋值(推荐)

修改JavaScript执行代码,通过创建信任策略将HTML内容转换为TrustedHTML后赋值:

# 替换原报错代码行
sb.driver.execute_script("""
// 创建信任策略
const policy = trustedTypes.createPolicy('gmail-html-policy', {
  createHTML: (html) => html
});
// 获取邮件正文元素并赋值
const emailBody = document.querySelector('div[role="textbox"]');
emailBody.innerHTML = policy.createHTML(arguments[0]);
""", body_content)

方法2:模拟剪贴板粘贴HTML

通过模拟用户粘贴操作插入HTML内容,绕过Trusted Types限制:

import pyperclip
from selenium.webdriver.common.by import By

# 将HTML内容写入剪贴板
pyperclip.copy(body_content)

# 定位邮件正文区域并触发粘贴
email_body = sb.driver.find_element(By.CSS_SELECTOR, 'div[role="textbox"]')
email_body.click()
sb.driver.execute_script("document.execCommand('paste');")

注意:需确保Chrome启动时添加剪贴板权限参数:

from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--enable-clipboard-read")
chrome_options.add_argument("--enable-clipboard-write")

方法3:禁用Trusted Types(临时测试用,不推荐)

通过Chrome启动参数关闭Trusted Types机制,仅适合本地测试:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--disable-features=TrustedTypes")
# 初始化driver时传入options
driver = webdriver.Chrome(options=chrome_options)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:37:02