python - 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 选择器的许多变体,例如:
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()
我也试过睡眠定时器。
该按钮位于当您按下上一个按钮时打开的窗口中,如果有帮助,背景会显示为灰色。图片。
# 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()
我希望程序按下按钮,但它没有,它只是坐在那里。
解决方案
所需元素位于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
推荐阅读
- python - 转置列表 - Python
- reactjs - React - 将 cookie 发送到 Express
- amazon-web-services - 尝试在 ECS 上的 CI/CD 管道中执行 Blue Green Deploy 时卡在 Code Deploy
- jmeter - JMeter HTML 报告:显示所有失败的交易都在 HTML 报告中传递
- java - 如何通过 Java/Kotlin API 从 KeyCloak 请求 JWT 令牌
- excel - 复制数据并重新排序列并粘贴到另一个工作簿
- openedge - 想要在任何数据字段中搜索所有包含“kan”的客户
- php - 如何在 PHP 中删除对象数组
- datatable - 动态启用数据表中的排序
- python - Pythin gi 模块和 OSX Catalina 之间是否存在冲突?