Mark K
Mark K

Reputation: 9348

Loop over list of elements for find_element_by_xpath() by Selenium and Webdriver

With Python, Selenium and Webdriver, a need to subsequently click elements found by texts, using the find_element_by_xpath() way on a webpage.

(an company internal webpage so excuse me cannot provide the url)

By xpath is the best way but there are multiple texts I want to locate and click.

It works when separately like:

driver.find_element_by_xpath("//*[contains(text(), 'Kate')]").click()

For multiple, here is what I tried:

name_list = ["Kate", "David"]

for name in name_list:
    xpath = "//*[contains(text(), '"
    xpath += str(name)
    xpath += "')]"
    print xpath
    driver.find_element_by_xpath(xpath).click()
    time.sleep(5)

The output of the print xpath looked ok however selenium says:

common.exceptions.NoSuchElementException

Upvotes: 1

Views: 3823

Answers (3)

min2bro
min2bro

Reputation: 4628

Use string formatting. Put a placeholder into the xpath string and fill it with a variable value:

name_list = ["Kate", "David"]

for name in name_list:
    xpath = "//*[contains(text(),'{}')]".format(name)  
    driver.find_element_by_xpath(xpath).click()

Upvotes: 2

Andrei
Andrei

Reputation: 5637

Try this:

name_list = ["Kate", "David"]

for name in name_list:
    xpath = "//*[contains(text(), '" + str(name) + "')]" # simplified
    print xpath
    list = driver.find_elements_by_xpath(xpath) # locate all elements by xpath
    if len(list) > 0: # if list is not empty, click on element
        list[0].click() # click on the first element in the list
    time.sleep(5)

This will prevent from throwing

common.exceptions.NoSuchElementException

Note: also make sure, that you using the correct xPath.

Upvotes: 1

Andersson
Andersson

Reputation: 52665

You can simplify your code as below:

for name in name_list:
    driver.find_element_by_xpath("//*[contains(text(), '%s')]" % name).click()

or

for name in name_list:
    try:
        driver.find_element_by_xpath("//*[contains(text(), '{}')]".format(name)).click()
    except:
        print("Element with name '%s' is not found" % name)

Upvotes: 2

Related Questions