首页 > 解决方案 > Selenium:try/except - driver.driver.find_element_by_xpath().click - 无法传递“selenium.common.exceptions.NoSuchElementException”

问题描述

我正在尝试/除了这里:

try:
    driver.find_element_by_xpath("/html/body/div[5]/div/div[1]/div[2]/div/div/article/table/tbody/tr[10]/td/a").click()
except NoSuchElementException:
    driver.find_element_by_xpath("/html/body/div[5]/div/div[1]/div[2]/div/div/article/table/tbody/tr[11]/td/a").click()

我总是得到:selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”:“/html/body/div[5]/div/div [1]/div[2]/div/div/article/table/tbody/tr[10]/td/span[1]"}

笔记:

  1. 我试过了:“尝试/除外”
  2. 我试过:“尝试/除了 NoSuchElementException”
  3. “从 selenium.common.exceptions 导入 NoSuchElementException”
  4. 我努力了:
try:
    test = driver.find_element_by_xpath("/html/body/div[5]/div/div[1]/div[2]/div/div/article/table/tbody/tr[10]/td/a")
    test_click = test.click()
except NoSuchElementException:
    driver.find_element_by_xpath("/html/body/div[5]/div/div[1]/div[2]/div/div/article/table/tbody/tr[11]/td/a").click()

仍然无法使其工作。

标签: seleniumtry-except

解决方案


您可以尝试以下解决方案以避免同步错误。

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By

try:
    element = WebDriverWait(driver, 20).until(
          EC.presence_of_element_located((By.XPATH, your element )))
except TimeoutException as ex:
            print ex.message

推荐阅读