python - 使用无头 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元素)
但是,当我放大渲染图像时,您可以看到非无头浏览器的分辨率要高得多(右侧):
那么这怎么可能,以及如何使用无头图像获得右侧图像的分辨率(由非无头浏览器生成)?我试图增加无头浏览器的窗口分辨率,但是,这不会缩放网站内容,如下图所示:
所以放大后它仍然是文本,按钮等的较低分辨率......
我该如何解决?有没有办法例如设置每英寸像素?
解决方案
因此,如果有人感兴趣,我可能找到了解决方案。由于我使用的是 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)
推荐阅读
- node.js - 使用 Mocha 进行 NodeJS EventEmitter 测试
- python-3.x - 在 Tensorflow 中,我不能在动态解码中使用任何 MultiRNNCell 实例,但可以使用单个 RNNCell 实例
- java - 在payara微战争文件中包含与POSTGRES的数据库连接的正确方法
- .net - .NET Core 2.1 - 如何创建 COM 对象并生成 *.tlb 文件
- ios - 更改符号名称和嵌入位码
- excel - Excel - 将值更改为另一个单元格的公式
- django - Django 2.1 查看权限
- apache-kafka - 如何使用 java 从 apache kafka 开始使用所有消息
- google-cloud-platform - 在对话流中,如何以编程方式上传包含问题和答案的文件?
- c++ - C ++中的浮点错误