Selenium和Webdriver遍历find_element_by_xpath()的元素列表

时间:2018-07-09 07:37:02

标签: python selenium selenium-webdriver xpath

使用Python,Selenium和Webdriver,需要随后使用网页上的find_element_by_xpath()方法单击文本找到的元素。

(公司内部网页,所以不能提供网址)

通过xpath是最好的方法,但是我想找到并单击多个文本。

它可以单独工作,如:

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

对于多个,这是我尝试的:

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)

print xpath的输出看起来不错,但是硒表示:

common.exceptions.NoSuchElementException

3 个答案:

答案 0 :(得分:2)

您可以如下简化代码:

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

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)

答案 1 :(得分:2)

使用字符串格式。将占位符放入xpath字符串中,并用变量值填充:

name_list = ["Kate", "David"]

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

答案 2 :(得分:1)

尝试一下:

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)

这将防止抛出

common.exceptions.NoSuchElementException

注意:还请确保您使用正确的xPath。