Using Selenium with Python to gather screenshots of the website

In my previous post, I provided a list of simple Selenium snippets I’m using regularly. This time I want to focus on the particular function – creating screenshots of the website and screenshots of the elements of the website.

Why screenshots?

Right now I’m using screenshots for two main reasons: for CSS regression tests and for exporting purposes.

CSS regression tests are useful when you are changing some widely used CSS properties and you want to check if the changes went well. In such a case you can gather screenshots of various pages of your website – prior to the change – and compare them to the screenshots of the page after the change.

When talking of exporting purposes – some of my clients want to export parts of the reports (charts) and save them to the Word document. In order to do this, I have to gether the screenshots of the particular elements of the page.

“Whole page” screenshot

The easiest way to generate the screenshot of the page is to use the following code:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://your-website.com')

driver.save_screenshot('page.png')

driver.quit()

The problem is that you will gather the screenshot of the part of the page which is visible in the browser. In order to gather the whole page, you can resize the browser to fit the whole page or gather the screenshot of the “body” element – see below.

Particular element screenshot

It is useful to gather screenshots of the part of the website. In my case, it is the particular chart I want to export to the Word document. The code is also really simple:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://your-website.com')

chart = driver.find_element_by_id('chart_id')
chart.screenshot('chart.png')

driver.quit()

As I mentioned above, it can also be useful to capture the whole page if the page is larger than the browser window. This is the code I use in such a case:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://your-website.com')

body = driver.find_element_by_tag_name('body')
body.screenshot('body.png')

driver.quit()

As you can see it is really simple yet powerful.

Leave a Reply

Your email address will not be published. Required fields are marked *