如何处理 Selenium 中的错误(无法定位元素)

How to handle errors (unable to locate element) in Selenium

我正在使用 Selenium 为一款需要大量点击的游戏编写机器人。 有时它显示错误无法定位元素:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div/div[1]/header/div/div[1]/a

我的 Xpath 是正确的,但有时它会在我的代码的不同部分给我一个错误。不是我有一个错误,它总是在一个地方显示错误。我的问题是这些错误是随机的。我是这样处理的:

try:
    secondPhoto = self.driver.find_element_by_xpath(
                    '/html/body/span/section/main/article/div[2]/div/div[1]/div[1]')
    secondPhotoOpen = ActionChains(self.driver)
    secondPhotoOpen.move_to_element(secondPhoto)
    secondPhotoOpen.click()
    secondPhotoOpen.perform()
except:
    time.sleep(3)
    self.driver.find_element_by_xpath(
                    '/html/body/span/section/main/article/div[1]/div/div/div[1]/div[2]').click()

这不是一个理想的解决方案。它仍然显示错误,但频率较低。 我也在使用 time.sleep。当我在 Internet 上做其他事情时通常会出现错误或者我有滞后(这就是我使用 time.sleep 的原因)现在,我的代码中有大约 50 .click() 并且对于所有点击我我正在尝试 except 但它仍然无法正常工作。

  1. 你有有效的解决方法吗?如何编写使用 .click() 的代码以 100% 确定其工作而不管滞后,其他 浏览器 activity?

  2. click()后如何等待下一个page/image满载(我是 使用 time.sleep)?

您可以使用 WebDriverWait:

btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "element_id")))
btn.click()

这将等待至少 10 秒,直到元素可点击,然后才点击它。我也建议阅读 this。使用 WebDriverWait,您不必硬编码暂停。