How to Take a Screenshot of a Website in Python Silently with Selenium
The code below will make a browser 1920px wide, and as long as the page and take its screenshot:
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By URL = 'https://msnbc.com' options = webdriver.ChromeOptions() options.headless = True driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) driver.get(URL) S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X) driver.set_window_size(1920,S('Height')) driver.find_element(By.TAG_NAME, 'body').screenshot('screenshot.png') driver.quit()
If the page needs to load asynchronously to complete building the DOM, you may need to give it a few seconds before taking the screenshot:
time.sleep(seconds)
If the page requires scrolling down to load the rest of the page:
scheight = .1 while scheight < 9.9: driver.execute_script("window.scrollTo(0, document.body.scrollHeight/%s);" % scheight) scheight += .01