简体   繁体   中英

A page contains 2 elements with the same “id”, how can I find the one I need?

I'm running a python script which fills out a form on a html page using selenium. The page contains 2 divs and one of them is hidden, they switch their state visible/hidden depending on a radio button. And those 2 divs have similar elements-inputs which have exactly the same id s. Hence, when I want to find an element in 2nd visible div, I actually find it in 1st invisible one.

# 2 elements with the same id on the page 
# one of them is hidden because it's in a hidden div

e1 = driver.find_element_by_id("some_id") 

How can I fix that?

One option would be to find all/both divs and filter the visible one :

visible_div = next(div for div in driver.find_elements_by_id("some_id") 
                   if div.is_displayed()) 

Or, you may just get the desired div by index (if this is applicable):

desired_div = driver.find_elements_by_id("some_id")[1]  # the second one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM