【问题标题】:Selenium + XPath: element not foundSelenium + XPath:找不到元素
【发布时间】:2018-08-30 08:44:48
【问题描述】:

我有一个 Selenium + Python + Chromedriver 脚本,它应该登录到一个网站并点击一个下载按钮,它将下载一个 CSV 文件。

检查下载按钮的详细信息是:

<button id="csv-button" class="block tiny-margin-top" data-args="csv">
      CSV
</button>

XPath 是:

//*[@id="csv-button"]

但是当我运行脚本时它说找不到 XPath 元素。请在下面找到代码:

click_button = driver.find_element_by_xpath('//*[@id="csv-button"]')
click_button.click()

【问题讨论】:

    标签: javascript python python-3.x selenium selenium-chromedriver


    【解决方案1】:

    如果您看到 element not found 异常,则在标识 WebElement 的唯一 xpath 的情况下,您需要将 WebDriverWaitexpected_conditions 子句设置为element_to_be_clickable 如下:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    # other code    
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='csv-button']"))).click()
    

    为了更细化,您可以使用:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    # other code    
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='block tiny-margin-top' and @id='csv-button']"))).click()
    

    【讨论】:

    • NameError: name 'WebDriverWait' is not defined
    【解决方案2】:

    问题似乎是您的 xpath 不太正确。您在需要双引号的地方使用单引号,反之亦然。

    试试:

    click_button = driver.find_element_by_xpath("//*[@id='csv-button']")
    click_button.click()
    

    你甚至可以尝试:

    //button[@id='csv-button']
    

    这将使 xpath 搜索更快,因为它只会查找按钮标签。

    【讨论】:

    • 没有。在 Python 中,没有使用单引号和双引号的规则,所以 "//*[@id='csv-button']"'//*[@id="csv-button"]' 一样正确
    【解决方案3】:

    单引号应该放在双引号中。请看下文

    click_button = driver.find_element_by_xpath("//*[@id='csv-button']")
    
    click_button.click()
    

    在此处查看更改:

    ('//*[@id="csv-button"]')   ---> ("//*[@id='csv-button']")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 2021-03-20
      • 2014-08-19
      • 1970-01-01
      • 2020-12-22
      • 2013-05-21
      相关资源
      最近更新 更多