我正在尝试在 python 中使用 selenium 按下一个按钮。我无法使用 xpath 或 css 选择器找到它。
对于脚本中的其余部分,我一直在使用 xpath,它工作正常,但每次打开时,此按钮的 xpath 似乎都是相对的。因此,我尝试使用 css 选择器访问 is。
我尝试访问的元素如下所示:
<button type="button" data-dismiss="modal" class="btn btn-primary pull-right">Opret AnnonceAgent</button>
chrome inspect 中的 css 选择器:
#\35 d167939-adc2-0901-34ea-406e6c26e1ab > div.modal-footer > div > button.btn.btn-primary.pull-right
如果我应该发布更多 html,请告诉我。
我试过很多堆栈溢出问题,也试过很多 css 选择器的变体,比如把它写成:
driver.find_element_by_class_name('#\35 d167939-adc2-0901-34ea-406e6c26e1ab.div.modal-footer.div.button.btn.btn-primary.pull-rightdiv.button.btn .btn-primary-pull-right').click()
driver.find_element_by_class_name('div.button.btn.btn-primary-pull-right').click()
driver.find_element_by_class_name('button.btn.btn-primary-pull-right').click()
driver.find_element_by_class_name('btn.btn-primary-pull-right').click()
driver.find_element_by_class_name('btn-primary-pull-right').click()
我也试过 sleep 定时器。
该按钮位于一个窗口中,当您按下上一个按钮时,该窗口将打开,背景为灰色(如果有帮助的话)。 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()
我希望程序按下按钮,但它没有,它只是坐在那里。
最佳答案
所需的元素位于模态对话框中,因此您需要诱导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
关于 python Selenium : Having trouble fixing NoSuchElementException for a specific button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55570708/