Find_element_by_name for multiple names

Question:

I want to find right element name by calling more element names at a time. Is that possible?

    try:
        G= driver.find_element_by_name("contact[Name]")
        G.send_keys("name")
    except: 
        pass
    try:
        H= driver.find_element_by_name("contact[name]")
        H.send_keys("name")
   
   elem = driver.find_element_by_name(("contact[Name]")("contact[name]"))
   elem.send_keys("name")
Asked By: M A Nezam Sagor

||

Answers:

I don’t think there’s a way to pass multiple names to find_element_by_name(). You’ll have to call it with the first name, and if that raises an exception, call it with the second name.

elem = None

try:
    elem = driver.find_element_by_name("contact[Name]")
except selenium.common.exceptions.NoSuchElementException:
    pass

if elem is None:
    # no element was found, so try again with the other name
    elem = driver.find_element_by_name("contact[name]")

elem.send_keys("whatever")

Or, a cleaner way to do the same thing in a loop:

elem = None

for element_name in ["some_name_1", "some_name_2"]:
    try:
        elem = driver.find_element_by_name(element_name)
        break
    except selenium.common.exceptions.NoSuchElementException:
        pass

elem.send_keys("whatever")
Answered By: John Gordon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.