繁体   English   中英

Selenium 元素截图抛出 WebDriverException 错误

[英]Selenium take screenshot of element throws WebDriverException error

我正在尝试运行谷歌搜索并截取我找到的图片。 出于某种未知原因,我的 web 驱动程序抛出此错误。

WebDriverException: Message: unknown command: session/311d692f492d13d74fe51827ad837d4e/screenshot/0.8100675049935289-1

这是我在这个例子中使用的代码我正在尝试截取谷歌搜索“长颈鹿”的第一张图片

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://images.google.com/')
x_path = '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input'
box = driver.find_element_by_xpath(x_path)
box.send_keys('Giraffe')
box.send_keys(Keys.ENTER)
element_2 = driver.find_element_by_xpath('//*[@id="sf"]/div[1]/div[1]/c-wiz/c-wiz/div/a/img').screenshot('user_path/test.png')

我尝试了不同的方法来打印结果。 我可以制作整个页面的驱动程序屏幕截图,但我想要每个元素。 我在网上看到了一些使用每张图片的 position 的解决方案,但这可能会有所不同,因为我希望运行许多不同的查询。

根据您的代码,我针对最新版本的 selenium 对其进行了稍微修改,使用略有不同的 xpath 位置找到第一张长颈鹿图像,滚动到它以使其可见,然后截屏:

def launch_url_screenshot(url):
    driver = webdriver.Chrome('driver/chromedriver')
    driver.get(url)
    x_path = '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input'
    box = driver.find_element(By.XPATH,x_path)
    box.send_keys('Giraffe')
    box.send_keys(Keys.ENTER)
    element_2 = driver.find_element(By.XPATH,'//*[@id="islrg"]/div[1]/div[1]/a[1]/div[1]/img')
    driver.execute_script('arguments[0].scrollIntoView({block: "center", inline: "center"})', element_2)
    element_2.screenshot('giraffe.png')

使用launch_url_screenshot('https://images.google.com/')调用它,它能够毫无错误地截屏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM