您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

除了硒以外,此示例还需要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才能实现的功能,那可能是一个可行的解决方案。

python 2022/1/1 18:26:39 有207人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶