小编典典

如何在python中使用Selenium WebDriver截取部分屏幕截图?

python

我为此进行了很多搜索,但找不到解决方案。这是java中可能的解决方案的类似问题

Python中有类似的解决方案吗?


阅读 312

收藏
2021-01-20

共1个答案

小编典典

除了硒以外,此示例还需要PIL映像库。有时将其作为标准库之一放入,有时却不作为,但如果没有,则可以使用pip install Pillow

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

fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
png = fox.get_screenshot_as_png() # saves screenshot of entire page
fox.quit()

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

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


im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

最后输出是… Stackoverflow徽标!!!

在此处输入图片说明

当然,现在仅获取静态图像将是过大的选择,但是如果您想要获取需要Javascript才能实现的功能,那可能是一个可行的解决方案。

2021-01-20