在Python中使用Selenium处理模态对话框

时间:2016-06-11 21:04:03

标签: python selenium

我正在使用Selenium来自动化流程,每次有人访问时,我想要交互的页面都会打开模式对话框。我希望能够正确地与主页面进行交互,因此我需要一种方法来关闭对话框。但是,我已经尝试了一些关于处理模态对话框的建议,但是他们没有按照他们的意愿工作。我可以点击两个按钮关闭对话框,其中一个是:

  <div class="modal-footer"> 
    <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button> 
  </div>

我尝试找到此按钮,然后点击它:

test = driver.find_element_by_link_text("Fechar")
test.click()

但这并没有关闭对话框。使用:

test = driver.find_element_by_link_text("Fechar")
test.send_keys(Keys.RETURN)

给了我以下错误:

no such element: Unable to locate element: {"method":"link text","selector":"Fechar"}.

我还想过编写一个脚本来使用TAB键在对话框中导航,然后在到达关闭按钮时按Enter键。但我不知道这是否是处理问题的正确方法,如果可以毫无问题地完成。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用find_element_by_link_text方法,您找不到按钮,您会找到一个链接元素(a)。 Reference

如果您想获得该按钮,可以使用:

driver.find_element_by_css_selector('.modal-footer > button[data-dismiss="modal"]')