简体   繁体   中英

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

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)

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

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.

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