首页 > 解决方案 > Selenium Python,我无法使用 xpath 找到元素 - NoSuchElementException

问题描述

我正在使用 Python3 + Selenium 在 Instagram 上登录,我正在使用 Google Chrome。当我登录时,我总是得到 2 个弹出窗口,我试图用它们的 xpath 找到它们以关闭它们。

不幸的是,Selenium 没有找到它们,而且我总是收到以下错误消息:

Traceback (most recent call last):
  File "mycode.py", line 61, in <module>
    driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]').click()

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]/div/div/div/div[3]/button[2]"}

我的代码:

# Load page
driver.get("https://www.instagram.com/accounts/login/")

# Login
driver.find_element_by_xpath("//div/input[@name='username']").send_keys(username)
driver.find_element_by_xpath("//div/input[@name='password']").send_keys(psw)
driver.find_element_by_xpath("//span/button").click()

print('1st popup window\n')
driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]').click()

print('2nd popup window\n')
driver.find_element_by_xpath("/html/body/div[2]/div/button").click()

我直接从浏览器中检索了 xpath,所以它不应该是这个问题的原因。有谁知道如何解决这个问题?谢谢!

标签: pythongoogle-chromeseleniuminstagramnosuchelementexception

解决方案


解决此问题的一种方法是使用显式等待。显式等待是您定义的代码,用于等待特定条件发生,然后再继续执行代码。也许按钮需要一些时间才能变得可见,在它可见之前,Selenium 会寻找它但找不到它,因此会引发错误。要解决此问题,请尝试以下操作:

button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "yourXPATH")))
button.click()

上面的代码最多会等待 10 秒,直到找到按钮元素;如果 10 秒内没有找到,Selenium 会抛出 TimeoutException 错误。

以下导入是代码正常工作所必需的:

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

更多关于显式等待的信息可以在这个网站上找到 - http://selenium-python.readthedocs.io/waits.html


推荐阅读