簡體   English   中英

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

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

使用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

您可以如下簡化代碼:

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)

使用字符串格式。 將占位符放入xpath字符串中,並用一個變量值填充它:

name_list = ["Kate", "David"]

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

嘗試這個:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM