我想截图Selenium中的一个元素,根据文档,每个WebElement都有一个功能:
屏幕截图(文件名)
将当前元素的屏幕截图保存为 PNG 图像文件。如果有任何 IOError,则返回 False,否则返回 True。在文件名中使用完整路径。
参数:文件名:您希望将屏幕截图保存到的完整路径。这应该以 .png 扩展名结尾
用法: element.screenshot('/Screenshots/foo.png')
但是,当我在我的程序中使用这个函数时:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
url='http://www.google.com'
browser = webdriver.Chrome()
browser.get(url)
content = browser.find_element_by_id('searchform')
content.screenshot('/home/ding/Pictures/shot.png')
Run Code Online (Sandbox Code Playgroud)
它引发这样的错误:
Traceback (most recent call last):
File "<ipython-input-8-309cb404878d>", line 11, in <module>
content.screenshot('/home/ding/Pictures/shot.png')
File "/home/ding/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 453, in screenshot
png = self.screenshot_as_png
File "/home/ding/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 435, in screenshot_as_png
return base64.b64decode(self.screenshot_as_base64.encode('ascii'))
File "/home/ding/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 425, in screenshot_as_base64
return self._execute(Command.ELEMENT_SCREENSHOT)['value']
File "/home/ding/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 501, in _execute
return self._parent.execute(command, params)
File "/home/ding/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute
self.error_handler.check_response(response)
File "/home/ding/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 165, in check_response
raise exception_class(value)
WebDriverException: unknown command: session/efbca24571c5332230f4d032ae04787c/element/0.7487814861441955-1/screenshot
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题并在 Python 中使用 Selenium 截取元素的屏幕截图?
您需要替换screenshotwithsave_screenshot方法。所以
代替 :
content.screenshot('/home/ding/Pictures/shot.png')
Run Code Online (Sandbox Code Playgroud)
使用 :
content.save_screenshot('/home/ding/Pictures/shot.png')
Run Code Online (Sandbox Code Playgroud)