Reputation: 508
I want to take screenshot of whole body of webpage, using Selenium and Gecko driver. However, when using headless mode, the resolution of output is much lower than in non-headless mode. I also checked the window_size
, but it is set to same values for headless and non-headless browser.
I have following code:
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)
Console output of this code is following:
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}
As you may noticed, resolution of body
element is almost same, also resolution of window (which is little lower for the GUI version, I believe it's because of the GUI elements)
However, when I zoom in rendered images, you can see that resolution of the non-headless browser is much higher (right side):
So how is this possible, and how can I get resolution of image on right side (generated by non-headless browser) using headless one? I tried to increase the resolution of window for headless browser, however, that does not scale the website content, as on following image:
So after zooming in it's still the lower resolution of text, buttons, etc...
How can I solve that? Is there any way to for example set pixels per inch?
Upvotes: 2
Views: 1267
Reputation: 508
So I probably found the solution, if anyone is interested in. As I am using Mac, it was needed to set different pixels per inch in Firefox Profile, so instead:
opts = webdriver.FirefoxOptions()
opts.headless = True
headlesssess = webdriver.Firefox(executable_path=os.getcwd()+"/geckodriver",options=opts)
it should be
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)
Upvotes: 2