1
votes

I am trying to click on a specific element that dynamically changes locations and therefore it changes xpaths and css selectors as well.

Tried xpath.

//*[@id="hld"]/div/div[X]/div[1]/h2/select

Note: The X will range from 2 to 10 depending on various factors.

There are no class names or IDs to use either. All I have to work with are the tag names.

My current code is as follows.

h2 = driver.find_element_by_tag_name("h2")
select = h2.find_element_by_tag_name("select")
select.click()

Unfortunately the select tag will load some time after the h2 tag, and I am trying to do a webdriverwait to wait until the element is clickable/visible before running the above code.

Sadly the proper syntax to single out the select element isn't clear to me. Below is the code to find the h2 tag, but I am trying to expand it out to focus in on the select tag.

WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.TAG_NAME, "h2")))

Any help is greatly appreciated.

1
Rather than working around, contact your developer and ask them to provide unique id for Select Tag. this would be the best and easy solution. - Gaurang Shah
@Tjj226_Angel Can you consider sharing the URL incase it is a public URL? Thanks - DebanjanB

1 Answers

0
votes

Try removing the dynamic div locator - the driver will iterate through the elements on the page and only click on it if it exists.

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait

xpath = ".//[@id="hld"]/div/div/div/h2/select"
timeout = 30    

WebDrierWait(driver, timeout).until(ec.presence_of_element_located(By.XPATH))

driver.find_element_by_xpath(xpath).click()

Otherwise, if the driver is finding multiple xpaths that match your xpath, you could try something like:

elements = driver.find_elements_by_xpath(xpath)

for element in elements:
   try:
      element.click()
    except ElementNotVisibleException:
       pass