selenium python element.screenshot() not working

Alex Bruce picture Alex Bruce · Mar 15, 2017 · Viewed 9.2k times · Source
 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

Answer

Chase G. picture Chase G. · Mar 15, 2017

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')