Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Modal Dialogs with Selenium in Python

I am using Selenium to automate a process and the page I want to interact to opens a modal dialog every time someone access it. I want to be able to interact with the main page properly, so I need a way to close the dialog. However, I've tried some suggestions on handling modal dialogs and they are not working as they should. There are two buttons I can click on to close the dialog, one of them is:

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

I've tried to locate this button and then click on it with:

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

But this is not closing the dialog. Using:

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

gives me the following error:

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

I've also thought of writing a script to navigate through the dialog using the TAB key and then hitting Enter when the close button is reached. But I don't know if this the proper way to handle the problem and if this can be done without issues. Thanks in advance.

like image 276
Vinícius Figueiredo Avatar asked Sep 06 '26 01:09

Vinícius Figueiredo


1 Answers

With find_element_by_link_text method, you won't find a button, you will find a link element (a). Reference.

If you want to get that button, you could use:

driver.find_element_by_css_selector('.modal-footer > button[data-dismiss="modal"]')
like image 150
Toni Villena Avatar answered Sep 07 '26 14:09

Toni Villena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!