我想把整个网页截图,使用Selenium和壁虎驱动。然而,当使用无头模式时,输出的分辨率比非无头模式低得多。我还检查了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元素的分辨率几乎是相同的,窗口的分辨率也是一样的(这在图形用户界面版本中略低,我相信这是因为图形用户界面元素)
但是,当我放大渲染的图像时,您可以看到非头浏览器的分辨率要高得多(右侧):

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

所以放大后它仍然是文本,按钮等的较低分辨率。
我该如何解决这个问题呢?例如,有没有办法设置每英寸的像素数?
发布于 2021-01-20 02:40:27
所以我可能找到了解决方案,如果有人感兴趣的话。由于我使用的是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)https://stackoverflow.com/questions/65797176
复制相似问题