3

I am trying to save particular element from html to be saved as image file using OpenCV and selenium. But unable to save the file.

from selenium import webdriver
import cv2
import numpy as np


browser = webdriver.Firefox()
browser.get(<URl with image>)

# Element to be saved
element = browser.find_element_by_id(<id of element>)

png = browser.get_screenshot_as_png()
location = element.location
size  = element.size

nparr = np.frombuffer(png, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)


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

im = img[left:right, top:bottom]

cv2.imwrite('filename.png',im)

Currently there is no image data in 'filename.png' by running this script.

abhi1610
  • 721
  • 13
  • 28
  • can you debug the values stored in `left`, `top`, `right` and `bottom` – ZdaR Jun 14 '18 at 04:54
  • `>>>print (left, top, right, bottom) >>>755 405 987.0 482.0` – abhi1610 Jun 14 '18 at 05:00
  • 1
    it would be better if you convert `right` and `bottom` to integer. Also can you debug `print img.shape` as well? One thing to note here is that you are cropping the `img` numpy matrix in wrong way, correct way of doing the same is `im= img[top:bottom, left:right]` – ZdaR Jun 14 '18 at 05:10
  • Thanks that resolves the issue. – abhi1610 Jun 14 '18 at 05:16
  • duplicate of [How to take partial screenshot with Selenium WebDriver in python?](https://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python) – Murthi Jun 14 '18 at 06:37
  • Possible duplicate of [How to take partial screenshot with Selenium WebDriver in python?](https://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python) – Murthi Jun 14 '18 at 06:38

1 Answers1

6

As mentioned by @Zdar I am writing the solution below:

from selenium import webdriver
import cv2
import numpy as np


browser = webdriver.Firefox()
browser.get(<URl with image>)

# Element to be saved
element = browser.find_element_by_id(<id of element>)

png = browser.get_screenshot_as_png()
location = element.location
size  = element.size

nparr = np.frombuffer(png, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)


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

#im = img[left:right, top:bottom]
im = img[top:int(bottom), left:int(right)]
cv2.imwrite('filename.png',im)
abhi1610
  • 721
  • 13
  • 28