How to click on an element identical to another element using selenium in python? How to click on an element identical to another element using selenium in python? selenium selenium

How to click on an element identical to another element using selenium in python?


Instead of direct fetching the element by classname you should fetch the using by id in the xpath because id of both the windows are different.
You can close the first window by using:

driver.find_element(By.XPATH, "//div[@id='ModalPopAmityHostel']//button[@class='close']").click()

And after clicking on first Close button you can click on the second close button in the similar fashion, you just need to replace id by StudentSatisfactionPop


z-index

The z-index CSS property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. So overlapping elements with a larger z-index cover those with a smaller one.


Comparing both the HTMLs you have provided the following element have a larger z-index and hence covers the other element.

<div id="ModalPopAmityHostel" class="modal fade in" role="dialog" aria-hidden="false" style="display: block;">    <div class="modal-dialog " style="z-index:104546464; ">

So you need to identify and click the x button of the above mentioned element first.


Solution

As the desired element is a Modal Dialog Box so to locate and click() on the desired element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#ModalPopAmityHostel div.modal-content>div.modal-header>button.close[data-dismiss='modal']"))).click()
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='ModalPopAmityHostel']//div[@class='modal-content']/div[@class='modal-header']/button[@class='close' and @data-dismiss='modal']"))).click()
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC