Joe
Joe

Reputation: 909

How to take a nice screenshot with Selenium?

I am trying to take a screenshot of a given website without scrolling down.

I'm using Selenium WebDriver for automation and I'm using Chromedriver.

Problem 1: I have noticed that when my driver runs and opens the chrome browser, it opens the browser with a small size. I tried the following but couldn't know how to set it to maximum and not take the scroll wheel on the right in the screenshot (see image below).

Problem 2: I want to block any chatbots or cookies so that I can take a clean screenshot (see image below).

The following is what I have tried.

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()

options.headless = False  # don't know sure what this does!
options.add_argument("--window-size=1700,1000")
options.add_argument("disable-popup-blocking")

options.add_experimental_option("prefs", {
                      "profile.default_content_setting_values.cookies": 2
                  }
)

driver = webdriver.Chrome(options=options)

URL = 'https://apploi.com/'

driver.get(URL)
sleep(1)

driver.get_screenshot_as_file('apploi.png')

driver.quit()
print("end...")

Desired screenshot output is to look like this:

enter image description here

Upvotes: 1

Views: 640

Answers (2)

Micky Rajkumar
Micky Rajkumar

Reputation: 1

import By

from selenium.webdriver.common.by import By

options.add_argument("--window-size=1920x1080")

add this to maximize your screen

options.add_argument("--start-maximized")

to remove cookie permission

cookie = driver.find_element(By.ID,'hs-eu-cookie-confirmation')
        driver.execute_script("""
        var element = arguments[0];
        element.parentNode.removeChild(element);
        """, cookie)

and lastly, add this to take screenshot

driver.save_screenshot("screenshot.png")

by the way you can remove this line. by default headless is false.

options.headless = False  # don't know sure what this does!

you can't run headless mode on that website

Upvotes: 0

Michael Mintz
Michael Mintz

Reputation: 15556

Here's a SeleniumBase pytest test that will do all that:

from seleniumbase import BaseCase

class MyTestClass(BaseCase):
    def test_screenshot(self):
        self.open("https://apploi.com/")
        self.remove_element("[data-nosnippet]")
        self.save_screenshot("my_screenshot.png")

Save that to a file, and run it with pytest after installing seleniumbase.

Upvotes: 2

Related Questions