gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:35 26 4
gpt4 key购买 nike

我想截取Selenium中的一个元素,根据文档,每个WebElement都有一个功能:

screenshot(filename)

Saves a screenshot of the current element to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename.

Args: filename: The full path you wish to save your screenshot to. This should end with a .png extension

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

它引发这样的错误:

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 截取元素的屏幕截图?

最佳答案

此代码非常适用于截取 Firefox 浏览器中特定元素的屏幕截图。

from selenium import webdriver
import io
from PIL import Image

fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')
image = fox.find_element_by_id('hlogo').screenshot_as_png
imageStream = io.BytesIO(image)
im = Image.open(imageStream)
im.save(image_path)

关于python - 如何使用Python截取Selenium中指定的WebElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com