How to handle multiple elements with the same ID in Selenium (auto-detect and interact)? [closed]

1 week ago 10
ARTICLE AD BOX

Yeap,​‍​‌‍​‍‌​‍​‌‍​‍‌ that kind of thing occurs when a website uses the same id for different elements multiple times (which really shouldn't be the case, but anyway). Selenium IDs to be unique, so it almost can't distinguish those pictures if you try to use find_element(By.ID) there.

The easiest way to resolve this problem is to totally ignore the ID and just fetch the <img> elements via XPath or CSS. For e.g. if all of them have the same ID but their src is different, you can just get them all like this:

images = driver.find_elements(By.XPATH, "//img[@id='Id']") for img in images: print(img.get_attribute("src"))

You can also do the same using CSS:

images = driver.find_elements(By.CSS_SELECTOR, "img#Id")

In the end, you can get through all the list elements and perform any actions you want .

It works this way because find_elements returns all the elements that match, even if the HTML is somewhat broken (like duplicated IDs). So rather than depending on the ID, you're basically handling them as a regular list of elements.

Moreover, if you want to locate an image using its src, this would work most of the time:

for img in images: if "target_image.png" in img.get_attribute("src"): img.click() break

So, yeah - it's better to skip find_element(By.ID) here. Selenium assumes that IDs are unique, and if the page is not following the rules, XPath/CSS is just a safer way to work ​‍​‌‍​‍‌​‍​‌‍​‍‌with.

Read Entire Article