Disclaimer: I know, that there is a similar question already, but none of the answers works for headless browser, so I have decided to make 1 more and a bit more detailed one (the question I have mentioned: Take screenshot of full page with Selenium Python with chromedriver)
Hello everyone.
I have stumbled upon a quite easy looking, yet hard to solve problem. I need to take a screenshot of a NON-HEADLESS BROWSER on a display, that is 1920x1080 (will be important later) that is going to make a screenshot of the whole webpage, not only the part that you can currently see.
What have I tried:
import os
import time
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument("--start-maximized")
chromedriver = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'chromedriver.exe')
chrome = webdriver.Chrome(chromedriver, options=chrome_options)
url = 'https://stackoverflow.com/'
chrome.get(url)
time.sleep(2)
total_height = chrome.execute_script("return document.body.parentNode.scrollHeight") + 1000
chrome.set_window_size(1920, total_height)
time.sleep(2)
chrome.save_screenshot("screenshot1.png")
chrome.quit()
^ this one, with Headless works perfectly fine, unfortunately, when I remove the --headless
option, selenium will try to resize itself, but since its trying to resize above the 1080
(height
of the display) its immediately adjusted to the 1080
which leads to a screenshot 1920x1080
. What I need in a "theoretical" way is to make selenium go headless
only for the moment, when its taking the screenshot (that unfortunatelly to my knowledge is not possible).
Other commonly used methods that does not work when browser is not headless:
el = driver.find_element_by_tag_name('body')
el.screenshot(path)
original_size = driver.get_window_size()
required_width = driver.execute_script('return document.body.parentNode.scrollWidth')
required_height = driver.execute_script('return document.body.parentNode.scrollHeight')
driver.set_window_size(required_width, required_height)
driver.find_element_by_tag_name('body').screenshot(path) # avoids scrollbar
driver.set_window_size(original_size['width'], original_size['height'])
element = chrome.find_element_by_tag_name('body')
element_png = element.screenshot_as_png
with open("test2.png", "wb") as file:
file.write(element_png)
With headless
option
Without headless
option