如何通过Selenium和Python单击模态窗口中的关闭按钮

问题描述 投票:0回答:2

无法在模态窗口中单击按钮id="close

尝试所有xpaths,如:

//button[@data-dismiss='modal']
//button[@id='close'], //button[@type='button']
//button[contains(.,'Закрыть')]
//button[contains(@data-dismiss,'modal')]
//button[contains(@id,'close')]

还试图结合xpaths,但仍然无法正常工作

码:

<div id="idCardGroupChangeStatusResult" class="modal fade in" tabindex="-1" role="dialog" aria-hidden="false" style="display: block;">
<div class="modal-dialog st-modal-dialog" style="width: 600px; padding-top: 250px;">
<div class="modal-content">
<div class="modal-header st-pad-normal">
<div class="modal-body">
<div class="modal-footer">
<button id="close" class="btn btn-default btn-sm" type="button" data-dismiss="modal"> Закрыть </button>
</div>
</div>
</div>
</div>

Css没有工作

有任何想法吗?

python selenium xpath css-selectors webdriverwait
2个回答
0
投票

如果element_to_be_clickable不起作用,请尝试下面的代码检查页面上是否有多个关闭按钮。您可以使用下面的代码按可见或可见和最新的代码进行过滤,然后单击它。

close_buttons = WebDriverWait(driver, 5).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#idCardGroupChangeStatusResult #close")))
# check how many buttons in on the HTML, you can try "visibility_of_all_elements_located"
print(len(close_buttons))

visible_buttons = [close_button for close_button in close_buttons if close_button.is_displayed()]
visible_buttons_len = len(visible_buttons)
print(visible_buttons_len)

visible_buttons[visible_buttons_len - 1].click()

消息是否消失?

更新,消息窗口消失:

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 as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)
actions = ActionChains(driver)

#...

status_message = wait.until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "#idCardGroupChangeStatusResult")))

actions.move_to_element(status_message).perform()
# here you can get text from message window, check/assert ..
status_message.find_element_by_css_selector("#close").click()

1
投票

由于文本为Закрыть的元素位于Modal Dialog Box内,因此要找到所需的元素,您必须引入WebDriverWait才能使元素可单击,您可以使用以下任一解决方案:

  • 使用CSS_SELECTORWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-default.btn-sm#close[data-dismiss='modal']"))).click()
  • 使用XPATHWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-default btn-sm' and @id='close'][@data-dismiss='modal']"))).click()
  • 注意:您必须添加以下导入: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
© www.soinside.com 2019 - 2024. All rights reserved.