簡體   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