如何使用Python在Selenium中截取指定的WebElement

时间:2017-11-10 13:50:33

标签: python selenium

我想在Selenium中截取一个元素,根据该文档,每个WebElement都有一个函数:

  

截图(文件名)

     

将当前元素的屏幕截图保存到PNG图像文件中。返回   如果存在任何IOError则返回false,否则返回True。使用文件名中的完整路径。

     

参数数量:   filename:您希望将屏幕截图保存到的完整路径。这应该以.png扩展名结尾

     

使用方法:   element.screenshot(“/截图/ 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')

它会引发这样的错误:

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

我如何解决这个问题,并在Python中使用Selenium截取元素的截图?

4 个答案:

答案 0 :(得分:0)

您需要使用screenshot方法替换save_screenshot。所以

而不是:

content.screenshot('/home/ding/Pictures/shot.png')

使用:

content.save_screenshot('/home/ding/Pictures/shot.png')

答案 1 :(得分:0)

此代码非常适合在Firefox浏览器中拍摄特定元素的屏幕截图。

K^{M - L}

答案 2 :(得分:0)

导入额外的库来编写文件对我来说似乎很愚蠢......

使用内置的 open

button_element = self._driver.find_element_by_class_name("a-button-input")
with open("element.png", "wb") as elem_file:
    elem_file.write(button_element.screenshot_as_png)

亚马逊元素输出:

enter image description here

答案 3 :(得分:-1)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep


url="http://www.google.com"
browser = webdriver.Chrome("c:\chrome\chromedriver.exe")
browser.get(url)
browser.find_element_by_id('searchform')
browser.save_screenshot("C://Demo//shot.png")