7
 from selenium import webdriver

 browser = webdriver.Chrome()
 browser.get("http://www.baidu.com")
 browser.find_element_by_id('su').screenshot('E:/test.png')
 browser.quit()

when I run above code, I got the errors,my python version is 2.7.13, selenium is 3.1

code error

[0315/220804.111:ERROR:angle_platform_impl.cc(33)] ANGLE Display::initialize err or 5: DXGI 1.2 required to present to HWNDs owned by another process. [0315/220804.111:ERROR:gl_surface_egl.cc(646)] eglInitialize D3D11 failed with e rror EGL_NOT_INITIALIZED, trying next display type Traceback (most recent call last): File "C:\Users\Administrator\Desktop\test.py", line 5, in browser.find_element_by_id('su').screenshot('E:/test.png') File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 443, in screenshot png = self.screenshot_as_png File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 430, in screenshot_as_png return base64.b64decode(self.screenshot_as_base64.encode('ascii')) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 420, in screenshot_as_base64 return self._execute(Command.ELEMENT_SCREENSHOT)['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 491, in _execute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l ine 238, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py" , line 164, in check_response raise exception_class(value) selenium.common.exceptions.WebDriverException: Message: unknown command: session /4a58c13f918aa319b2df6ef70ac2ca51/element/0.4724184220629968-1/screenshot

Jacques Gaudin
  • 12,304
  • 3
  • 40
  • 64
Alex Bruce
  • 495
  • 7
  • 21

1 Answers1

5

It doesn't look like you can screenshot a particular element with selenium alone. See here, for example: How to take screenshot of element using python3 and selenium.

There are workarounds such as this: How to take partial screenshot with Selenium WebDriver in python?.

You can also take a screenshot of the page and crop it. In that case, these work:

browser.get_screenshot_as_file('/example/file/path.png')

or

browser.save_screenshot('/example/file/path.png')
illright
  • 3,586
  • 2
  • 24
  • 43
Chase G.
  • 113
  • 5
  • What about http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.screenshot ? – GiriB Apr 21 '17 at 17:58
  • Has that worked for you? I've tried element.screenshot(file) a few times and it has never worked. That's what the original poster was trying also. – Chase G. Apr 21 '17 at 23:58
  • 1
    It seems that it has not been implemented yet. Take a look at [this](https://github.com/seleniumhq/selenium/issues/912). – GiriB Apr 23 '17 at 06:23