Skip to main content
 首页 » 编程设计

python之如何使用 Selenium 单击此按钮

2025年05月04日8jackei

以下是我尝试根据“检查”点击的元素的所有部分:

<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"> 
    ::before 
    <div class="ui-dialog-buttonset"> 
        <button type="button" class="done ui-button ui-corner-all ui-widget"> 
        Done</button> 
    </div> 
    ::after 
</div> 

当我想点击它时,我假设它在 ::before 上显示和可点击的部分。在代码中,我确保在单击之前滚动并等待两秒钟以确保按钮可见,但我得到:

selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable 

但我不明白它为什么不可交互。当我在检查器中将鼠标悬停在它上面时,<button>...</button> 中的所有内容突出显示,所以我要单击的按钮必须在那里,对吗?

以下是我尝试过的几件事:

browser.find_element_by_css_selector('button[type=button]').click() 
 
browser.find_elements_by_xpath("//*[contains(text(), 'Done')]").click() 
 
# The above returns a list for some reason? 
 
browser.find_elements_by_css_selector('done.ui-button.ui-corner-all.ui-widget') 

我希望我能记住我尝试过的一切,但无论如何我希望有人能帮助我。

请您参考如下方法:

要单击该元素,因为所需的元素是一个动态元素,您必须诱导 WebDriverWait 以使该元素可单击,并且您可以使用以下任一解决方案:

  • 使用 CSS_SELECTOR:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ui-dialog-buttonpane.ui-widget-content.ui-helper-clearfix"))).click() 
    
  • 使用 XPATH:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='ui-dialog-buttonpane ui-widget-content ui-helper-clearfix']"))).click() 
    
  • 注意:您必须添加以下导入:

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

You can find a detailed discussion in selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable using Selenium