我为此进行了很多搜索,但找不到解决方案。这是java中可能的解决方案的类似问题。
Python中有类似的解决方案吗?
除了硒以外,此示例还需要PIL映像库。有时将其作为标准库之一放入,有时却不作为,但如果没有,则可以使用pip install Pillow
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才能实现的功能,那可能是一个可行的解决方案。