Spvda
Spvda

Reputation: 23

How to capture a screenshot of a certain size of window with selenium?

I try to take of the whole screen, a capture of a small fragment. I try to take a screenshot with the dimensions (w, x, y, z) of the window. Where the photo takes the values:

w = 240, 200
x = 540, 200
y = 240, 600
z = 600, 600

But honestly, I don't know how to implement it in my code. Is this:

from selenium import webdriver
driver.save_screenshot(r'C:\Users\youna\Pictures\1\{}.png'.format(codigos_1[i]))

How could I do it?

Upvotes: 1

Views: 1929

Answers (1)

Prophet
Prophet

Reputation: 33351

You can take a screenshot of the entire screen and then crop from it the part according to desired dimensions.
This will be done with use of PIL Imaging library.
It can be installed with
pip install Pillow
The code can be as following:

from selenium import webdriver
from PIL import Image
from io import BytesIO

#save screenshot of entire page
png = driver.get_screenshot_as_png() 


#open image in memory with PIL library
im = Image.open(BytesIO(png))

#define crop points
im = im.crop((left, top, right, bottom))

#save new cropped image
im.save('screenshot.png')

where
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']

Upvotes: 3

Related Questions