首页 > 解决方案 > 使用无头 Firefox 时 Selenium 错误的屏幕截图分辨率

问题描述

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

我有以下代码:

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元素)

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

左侧无头,右侧无头

那么这怎么可能,以及如何使用无头图像获得右侧图像的分辨率(由非无头浏览器生成)?我试图增加无头浏览器的窗口分辨率,但是,这不会缩放网站内容,如下图所示: 在此处输入图像描述

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

我该如何解决?有没有办法例如设置每英寸像素?

标签: pythonseleniumfirefoxscreenshotgeckodriver

解决方案


因此,如果有人感兴趣,我可能找到了解决方案。由于我使用的是 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)

推荐阅读