Python Selenium:无法修复特定按钮的 NoSuchElementException

Python Selenium: Having trouble fixing NoSuchElementException for a specific button

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

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

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

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

chrome 中 inspect 的 css 选择器:

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

让我知道我是否应该 post 更多 html。

我尝试了很多堆栈溢出问题,并尝试了 css 选择器的许多变体,比如把它写成:

我也试过睡眠定时器。

该按钮位于 window 中,当您按下上一个按钮时会打开该按钮,如果有帮助,背景会变灰。 Picture.

# 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()

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

class_name 接收一个 class 作为参数,但您使用 css 语法作为定位符。

css_selector

driver.find_element_by_css_selector('button.btn.btn-primary-pull-right')

这意味着 <button> 标签有 2 个 class,btnbtn-primary-pull-right

class_name

driver.find_element_by_class_name('btn-primary-pull-right')

我的猜测是 right.There 是一个 iframe 停止访问 element.You 必须先切换到 iframe 才能访问 button element.Try 现在使用以下代码。

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

#WebDriverWait(driver,20).until(expected_conditions.frame_to_be_available_and_switch_to_it((By.XPATH,'//iframe[starts-with(@id,"rdr_")]')))
WebDriverWait(driver,20).until(expected_conditions.frame_to_be_available_and_switch_to_it((By.XPATH,'//iframe[@id="qualaroo_dnt_frame"]')))
driver.find_element_by_css_selector('button.btn.btn-primary').click()

所需的元素位于 模态对话框 中,因此您需要为所需的 元素引入 WebDriverWait可点击 并且您可以使用以下任一项 :

  • 使用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