如何在python中保存selenium和opencv的部分屏幕截图
我试图使用OpenCV和selenium将html中的特定元素保存为图像文件。但无法保存该文件如何在python中保存selenium和opencv的部分屏幕截图,python,selenium,numpy,opencv,crop,Python,Selenium,Numpy,Opencv,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 ele
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)
从selenium导入webdriver
进口cv2
将numpy作为np导入
browser=webdriver.Firefox()
browser.get()
#要保存的元素
元素=浏览器。按元素id()查找元素
png=浏览器。获取屏幕截图作为png()
位置=元素。位置
大小=元素大小
nparr=np.frombuffer(png,np.uint8)
img=cv2.imdecode(nparr,cv2.IMREAD\u颜色)
左=位置['x']
顶部=位置['y']
右=位置['x']+大小['width']
底部=位置['y']+尺寸['height']
im=img[左:右,上:下]
imwrite('filename.png',im)
通过运行此脚本,
'filename.png'
中目前没有图像数据。正如@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)
从selenium导入webdriver
进口cv2
将numpy作为np导入
browser=webdriver.Firefox()
browser.get()
#要保存的元素
元素=浏览器。按元素id()查找元素
png=浏览器。获取屏幕截图作为png()
位置=元素。位置
大小=元素大小
nparr=np.frombuffer(png,np.uint8)
img=cv2.imdecode(nparr,cv2.IMREAD\u颜色)
左=位置['x']
顶部=位置['y']
右=位置['x']+大小['width']
底部=位置['y']+尺寸['height']
#im=img[左:右,上:下]
im=img[顶部:整数(底部),左侧:整数(右侧)]
imwrite('filename.png',im)
你能调试存储在左
、上
、右
和下
打印(左、上、右、下)>>755 405 987.0 482.0
中的值吗如果你把右
和下
转换成整数会更好。您还可以调试打印img.shape
吗?这里需要注意的一点是,您以错误的方式裁剪了img
numpy矩阵,正确的方法是im=img[top:bottom,left:right]
,谢谢您解决了这个问题。重复的