如何在python中保存selenium和opencv的部分屏幕截图

abh*_*610 3 python selenium opencv numpy crop

我正在尝试使用 OpenCV 和 selenium 将 html 中的特定元素保存为图像文件。但无法保存文件。

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)
Run Code Online (Sandbox Code Playgroud)

'filename.png'目前运行此脚本没有图像数据。

abh*_*610 6

正如 @Zdar 所提到的,我正在编写以下解决方案:

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)
Run Code Online (Sandbox Code Playgroud)