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

发布于 2021-01-29 14:57:55

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

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

关注者
0
被浏览
98
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看