如何在 python 中使用 Selenium WebDriver 截取部分截图?
·
回答问题
我为此搜索了很多,但找不到解决方案。这是一个类似的问题在java中可能的解决方案。
Python中有类似的解决方案吗?
Answers
除了 Selenium,此示例还需要 PIL Imaging 库。有时这是作为标准库之一,有时不是,但如果你没有它,你可以用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 才能实现的东西,这可能是一个可行的解决方案。
更多推荐

所有评论(0)