首页 > 解决方案 > Python Selenium:修复特定按钮的 NoSuchElementException 时遇到问题

问题描述

我正在尝试在 python 中按下带有硒的按钮。我无法使用 xpath 或 css 选择器找到它。

对于脚本中的其他内容,我一直在使用 xpath,它工作正常,但是每次打开这个按钮的 xpath 似乎都是相对的。因此,我尝试使用 css 选择器访问。

我试图访问的元素如下所示:

<button type="button" data-dismiss="modal" class="btn btn-primary pull-right">Opret AnnonceAgent</button>

chrome中检查的css选择器:

#\35 d167939-adc2-0901-34ea-406e6c26e1ab > div.modal-footer > div > button.btn.btn-primary.pull-right

让我知道我是否应该发布更多的html。

我尝试了许多堆栈 oveflow 问题,并尝试了 css 选择器的许多变体,例如:

我也试过睡眠定时器。

该按钮位于当您按下上一个按钮时打开的窗口中,如果有帮助,背景会显示为灰色。图片

# This opens up the window in which to press the next button (works fine)
button = driver.find_element_by_xpath('//*[@id="content"]/div[1]/section/div[2]/button')
button.click()
driver.implicitly_wait(15)
time.sleep(5)
# This is what doesn't work
driver.find_element_by_class_name('button.btn.btn-primary-pull-right').click()

我希望程序按下按钮,但它没有,它只是坐在那里。

标签: pythonseleniumselenium-webdriverwebdriverwebdriverwait

解决方案


所需元素位于Modal Dialog Box中,因此您需要诱导WebDriverWait以使所需元素可点击,并且您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary.pull-right[data-dismiss='modal']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary pull-right' and @data-dismiss='modal'][text()='Opret AnnonceAgent']"))).click()
    
  • 注意:您必须添加以下导入:

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

推荐阅读