Welcome
admin
admin

2025-08-19 19:44:04

葡萄牙世界杯球员
4989 475

免责声明:我知道,已经有一个类似的问题,但没有一个答案适用于无头浏览器,所以我决定再做一个更详细的问题(我提到的问题:Take screenshot of full page with Selenium Python with chromedriver)

大家好。

我偶然发现了一个看起来很容易,但很难解决的问题。我需要在显示器上截取一个非头部浏览器的屏幕截图,即1920x1080 (稍后会很重要),它将会截取整个网页的屏幕截图,而不仅仅是你当前可以看到的部分。

我尝试了什么:

代码语言:javascript运行复制import os

import time

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()

chrome_options.add_argument('--headless')

chrome_options.add_argument("--start-maximized")

chromedriver = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'chromedriver.exe')

chrome = webdriver.Chrome(chromedriver, options=chrome_options)

url = 'https://stackoverflow.com/'

chrome.get(url)

time.sleep(2)

total_height = chrome.execute_script("return document.body.parentNode.scrollHeight") + 1000

chrome.set_window_size(1920, total_height)

time.sleep(2)

chrome.save_screenshot("screenshot1.png")

chrome.quit()^这一个,无头工作完全正常,不幸的是,当我删除--headless选项时,selenium会尝试调整自己的大小,但由于它试图在1080 (height of the display)上调整大小,因此它立即调整为1080,这会导致屏幕截图1920x1080。我需要的“理论”方式是让selenium只在截图的时候使用headless (不幸的是,据我所知这是不可能的)。

当浏览器不是无头时不起作用的其他常用方法:

代码语言:javascript运行复制el = driver.find_element_by_tag_name('body')

el.screenshot(path)代码语言:javascript运行复制original_size = driver.get_window_size()

required_width = driver.execute_script('return document.body.parentNode.scrollWidth')

required_height = driver.execute_script('return document.body.parentNode.scrollHeight')

driver.set_window_size(required_width, required_height)

driver.find_element_by_tag_name('body').screenshot(path) # avoids scrollbar

driver.set_window_size(original_size['width'], original_size['height'])代码语言:javascript运行复制element = chrome.find_element_by_tag_name('body')

element_png = element.screenshot_as_png

with open("test2.png", "wb") as file:

file.write(element_png)使用headless选项

不带headless选项