【问题标题】:Selenium does not take the screenshot of the whole website, when its not headlessSelenium 不会截取整个网站的截图,当它不是无头时
【发布时间】:2021-11-13 13:56:52
【问题描述】:

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

大家好。

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

我尝试了什么:

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 工作得非常好,不幸的是,当我删除 --headless 选项时,selenium 会尝试调整自己的大小,但是因为它试图调整大小高于 1080(显示器的height)它立即调整为1080,从而导致屏幕截图1920x1080。我需要以“理论上”的方式使 selenium 仅在截屏时使用headless(不幸的是,据我所知这是不可能的)。

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

el = driver.find_element_by_tag_name('body')
el.screenshot(path)
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'])
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 选项

【问题讨论】:

    标签: python selenium google-chrome selenium-webdriver selenium-chromedriver


    【解决方案1】:

    您可以使用 Screenshot_Clipping 来滚动页面并从每个滚动处截取屏幕截图。

    只需在 python3 中运行此命令

    pip install Selenium-Screenshot
    

    然后创建一个截图对象:

    ob=Screenshot_Clipping.Screenshot()
    

    使用该对象,您可以使用ob.full_Screenshot 来捕获全屏

    在 Github 上查看 PythonFullPageScreenShot 项目以获取完整源代码

    请注意,截图只能截取网站高度的 10000,您可以缩放到 100 以捕获全高

    【讨论】:

    • 嗨,答案似乎是我希望它工作的方式。无论如何,我对此有一个疑问……有没有一种简单的方法可以使该屏幕截图不被剪切? (页面的一些地方丢失了。我玩过“视口”宽度和高度,但它看起来不像它的工作。提前谢谢:)
    • 找到了正确的方法 我输入了该消息:D ...没有注意到我可以轻松地操纵viewport_height。谢谢你的回答!尽管如此,如果它能够以某种方式自动化就好了
    • 如果有人没有提出更好的解决方案,我会再等几天,如果没有,我会接受这个答案:)
    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 2019-11-09
    • 2021-07-12
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多