python - selenium 无法截屏网页元素

标签 python selenium firefox

enter image description here

我可以使用 Firefox.get_screenshot_as_file('2.png') 截取整个页面,但是当我使用 passage.screenshot('1.png') 截取 Web 元素时,它总是引发此异常:

selenium.common.exceptions.WebDriverException: Message: Unrecognized command: GET /session/284283fa-53fc-4b33-b329-e6e888dbdcb0/screenshot/{35834cf1-c9c7-4129-99b1-24f30c6b56e6}

最佳答案

你得到这个异常是因为你不能在没有一些第三方库或你自己的代码来处理这个的情况下只截取 selenium 中的一个元素。参见 This stackoverflow post

它使用名为 PIL 的库来执行此操作:

from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('https://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
fox.save_screenshot('screenshot.png') # saves screenshot of entire page
fox.quit()

im = Image.open('screenshot.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

关于python - selenium 无法截屏网页元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564932/

相关文章:

python - 终止子进程的命令执行

python - 调试时在 pool.close() 上抛出异常,但在运行时不会

selenium - Protractor 最大调用堆栈错误

java - Webdriver sendkeys() 不起作用。使用 javascript 也失败

html - 标签/输入在 Firefox 中的定位不同于 Chrome/Safari

javascript - firefox 与 Chrome 之间的边距顶部是不同的

css - Firefox 上的额外边框 div 但 Safari 或 Chrome 中没有

python - 枕头无法读取不同的 TIFF 文件

带有 Selenium WebDriver 的 Java8

python - 从数组生成依赖组合