Home > database >  Find_element_by_name for multiple names
Find_element_by_name for multiple names

Time:11-29

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")

CodePudding user response:

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")
  • Related