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

Python+Selenium新Headless模式下窗口大小与截图尺寸不符问题

问题原因及解决方案

尺寸差异的原因

  1. 参数冲突:你同时配置了--window-size=800,600和--start-fullscreen参数,这两个参数存在冲突。--start-fullscreen会强制Chrome进入全屏模式,直接覆盖你设置的窗口尺寸配置,导致实际渲染的视口并非800x600。
  2. 高DPI缩放影响:新Headless模式下,Chrome默认会继承系统的DPI缩放比例。你的截图尺寸1574×1188正好是800×600乘以约1.96-1.98倍的缩放比例,说明系统的高DPI缩放被应用到了Headless Chrome上,导致截图尺寸被放大。

解决方法

  1. 移除冲突参数:删除--start-fullscreen参数,避免它覆盖窗口尺寸设置。
  2. 强制禁用DPI缩放:添加--force-device-scale-factor=1参数,强制Chrome使用1倍缩放比例,确保截图尺寸与设置的窗口尺寸一致。

修改后的代码如下:

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

options = Options()
options.add_experimental_option("excludeSwitches", ['enable-automation'])
options.add_argument('--headless=new')
options.add_argument("--window-size=800,600")
# 添加强制缩放参数,禁用系统DPI缩放
options.add_argument("--force-device-scale-factor=1")
driver = webdriver.Chrome(options=options)
driver.get(f"https://www.google.com/")
sleep(1)
print(driver.get_window_size()) # 返回{'width': 800, 'height': 600}
driver.get_screenshot_as_file("./tmp.png")
driver.quit()

执行上述代码后,生成的tmp.png尺寸会和你设置的800×600一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:52:33