首页 > 解决方案 > 如何根据 Selenium 和 Python 提供的 HTML 定位元素

问题描述

我正在尝试在 Python 中使用 Selenium 单击“下一步”按钮,其源代码为:

<div class="form-group clearfix">
            <button id="experiment-method-previous" type="button" class="btn btn-dark pull-left" ng-click="navigate('run',$event)">Previous</button>
            <button id="experiment-method-next" type="button" class="btn btn-primary pull-right" ng-click="navigate('export',$event)">Next</button>
        </div>

我使用这条线:

driver.find_element_by_id('experiment-method-next')

但我收到此错误:

Unable to locate element: [id="experiment-method-next"]

相同的

driver.find_element_by_class_name('btn btn-primary pull-right')
Unable to locate element: .btn btn-primary pull-right

有什么想法吗?

标签: pythonseleniumselenium-webdriverxpathcss-selectors

解决方案


根据您共享的HTMLclick(),以使用文本调用元素作为Next,您必须诱导WebDriverWait以使所需元素可单击,并且您可以使用以下任一解决方案:

  • CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary.pull-right#experiment-method-next"))).click()
    
  • XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary pull-right' and @id='experiment-method-next']"))).click()
    

注意:您必须添加以下导入:

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

推荐阅读