【问题标题】:Selenium Python, I can't find the element with xpath - NoSuchElementExceptionSelenium Python,我找不到 xpath 的元素 - NoSuchElementException
【发布时间】:2018-07-20 17:51:38
【问题描述】:

我正在使用 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,所以它不应该是这个问题的原因。有谁知道如何解决这个问题? 谢谢!

【问题讨论】:

    标签: python google-chrome selenium instagram nosuchelementexception


    【解决方案1】:

    解决此问题的一种方法是使用显式等待。显式等待是您定义的代码,用于等待特定条件发生,然后再继续执行代码。也许按钮需要一些时间才能变得可见,在它可见之前,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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2023-02-20
      • 1970-01-01
      相关资源
      最近更新 更多