python - 使用 Headless Firefox 时 Selenium 的屏幕截图分辨率错误

标签 python selenium firefox screenshot geckodriver

我想使用 Selenium 和 Gecko 驱动程序截取整个网页的屏幕截图。然而,当使用 headless 模式时,输出的分辨率比非 headless 模式低得多。我还检查了 window_size,但它对于 headless 和非 headless 浏览器设置为相同的值。

我有以下代码:

from selenium import webdriver
import os

#headless browser
opts = webdriver.FirefoxOptions()
opts.headless = True
headlesssess = webdriver.Firefox(executable_path=os.getcwd()+"/geckodriver",options=opts)
headlesssess.set_window_size(1920,1080)

print('window size with headless is', headlesssess.get_window_size())
headlesssess.get('https://www.stackoverflow.com')
elem = headlesssess.find_element_by_tag_name('body')

print('body size with headless is ', elem.size)
elem_png = elem.screenshot_as_png
with open('test_headless.png','wb') as f:
    f.write(elem_png)

#non-headless browser
opts = webdriver.FirefoxOptions()
opts.headless = False
headsess = webdriver.Firefox(executable_path=os.getcwd()+"/geckodriver",options=opts)
headsess.set_window_size(1920,1080)

print('window size with head is ', headsess.get_window_size())
headsess.get('https://www.stackoverflow.com')
elem = headsess.find_element_by_tag_name('body')

print('body size with head is ', elem.size)
elem_png = elem.screenshot_as_png
with open('test_head.png','wb') as f:
    f.write(elem_png)

此代码的控制台输出如下:

window size with headless is {'width': 1920, 'height': 1080}
body size with headless is  {'height': 5880.68310546875, 'width': 1920.0}
window size with head is  {'width': 1792, 'height': 1045}
body size with head is  {'height': 5880.216796875, 'width': 1777.0}

正如您可能注意到的,body 元素的分辨率几乎相同,窗口的分辨率也几乎相同(GUI 版本的分辨率稍低,我相信这是因为 GUI 元素的原因)

但是,当我放大渲染图像时,您可以看到非 headless 浏览器的分辨率要高得多(右侧):

headless on left side, non-headless on right side

那么这怎么可能,以及如何使用 headless 浏览器获得右侧图像的分辨率(由非 headless 浏览器生成)?我尝试增加 headless 浏览器的窗口分辨率,但是,这不会缩放网站内容,如下图所示: enter image description here

所以放大后仍然是文本、按钮等的较低分辨率...

我该如何解决这个问题?有什么方法可以设置每英寸的像素数吗?

最佳答案

所以如果有人感兴趣的话,我可能找到了解决方案。由于我使用的是 Mac,因此需要在 Firefox 配置文件中设置每英寸不同的像素,因此:

opts = webdriver.FirefoxOptions()
opts.headless = True
headlesssess = webdriver.Firefox(executable_path=os.getcwd()+"/geckodriver",options=opts)

应该是

prof = webdriver.FirefoxProfile()
prof.set_preference('layout.css.devPixelsPerPx','2.0') #this sets high resolution
headlesssess = webdriver.Firefox(executable_path=os.getcwd()+"/geckodriver",options=opts,firefox_profile=prof)

关于python - 使用 Headless Firefox 时 Selenium 的屏幕截图分辨率错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65797176/

相关文章:

html - 背景图像未在 Firefox 中加载

c++ - RGB 颜色到 HSL 字节

python - Python 中的统一成本搜索

java - Appium 1.13 IOS 12.3.1 切换到 webview(NewTab) 上下文时操作超时

java - 如何使用 Selenium WebDriver 查找在每个页面加载时动态 ID/名称发生变化的元素

Javascript 无法在 Chrome 中的 <input type ="button"> 上单击()

python - 用Python编码有向图的 bool 邻接矩阵

python - 如何在 Django 中链接我的 css、js 和图像文件链接

javascript - 内联 svg 作为指令(Firefox 问题)

javascript - 无法通过 websocket 将视频流式传输到 Firefox