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

Chrome Headless模式触发JavascriptException问题求助

解决Headless模式下元素无尺寸位置的JavascriptException错误

当Chrome浏览器设置headless=True运行网页抓取脚本时,触发以下JavascriptException错误:

JavascriptException: Message: javascript error: {"status":60,"value":"[object HTMLButtonElement] has no size and location"}
(Session info: chrome-headless-shell=124.0.6367.119)

而设置headless=False时脚本运行正常,问题根源在于Headless模式默认窗口尺寸过小,导致目标元素未被正常渲染(无尺寸和位置信息),同时使用ActionChains的移动点击逻辑放大了这个问题。

修复方案

1. 初始化时设置Headless窗口尺寸

Headless模式默认窗口极小,显式设置合理的窗口尺寸,确保元素能被完整渲染:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
# 使用新版Headless模式,行为更接近正常浏览器
chrome_options.add_argument("--headless=new")
# 设置窗口尺寸为常见的1080P分辨率
chrome_options.add_argument("--window-size=1920,1080")
# 禁用GPU,避免部分环境兼容性问题
chrome_options.add_argument("--disable-gpu")

driver = webdriver.Chrome(options=chrome_options)

2. 替换ActionChains点击为直接元素点击

如果元素本身处于可交互状态,直接调用element.click()比ActionChains的移动点击更稳定,无需依赖元素的位置信息:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException, TimeoutException

try:
    # 显式等待元素可点击,替代隐式等待
    select_store = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//button[@class="cc-btn cc-btn--secondaryC js-selectStore"][@data-storename="FIRENZE NOVOLI"]'))
    )
    driver.save_screenshot('click7.png')
    # 直接点击元素
    select_store.click()
    driver.save_screenshot('click8.png')
except StaleElementReferenceException:
    driver.save_screenshot('click9.png')
    # 重新等待并获取元素
    select_store = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//button[@class="cc-btn cc-btn--secondaryC js-selectStore"][@data-storename="FIRENZE NOVOLI"]'))
    )
    driver.save_screenshot('click10.png')
    select_store.click()
    driver.save_screenshot('click11.png')
except TimeoutException:
    print("元素超时未加载或无法点击")

3. 兜底方案:使用JS点击

如果上述方法仍无效,可通过JavaScript强制点击元素,绕过元素可见性和位置的限制:

# 替换select_store.click()为以下代码
driver.execute_script("arguments[0].click();", select_store)

关键说明

  • 优先使用新版Headless模式(--headless=new),它的渲染逻辑更接近正常浏览器,能减少此类兼容性问题。
  • 显式等待比隐式等待更精准,确保操作时元素处于预期状态,避免因页面加载延迟导致的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:51:20