Python Selenium和Webdriver通过xpath()查找元素的元素列表

Python Selenium和Webdriver通过xpath()查找元素的元素列表,python,selenium,selenium-webdriver,xpath,Python,Selenium,Selenium Webdriver,Xpath,对于Python、Selenium和Webdriver,接下来需要在网页上使用find_element_by_xpath()方式单击由文本找到的元素 (公司内部网页,请原谅,无法提供url) 通过xpath是最好的方法,但是我想找到并单击多个文本 它在以下情况下单独工作: driver.find_element_by_xpath("//*[contains(text(), 'Kate')]").click() 对于multiple,以下是我尝试的内容: name_list = ["Kate",

对于Python、Selenium和Webdriver,接下来需要在网页上使用find_element_by_xpath()方式单击由文本找到的元素

(公司内部网页,请原谅,无法提供url)

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

它在以下情况下单独工作:

driver.find_element_by_xpath("//*[contains(text(), 'Kate')]").click()
对于multiple,以下是我尝试的内容:

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)
打印xpath的输出看起来正常,但selenium表示:

common.exceptions.NoSuchElementException
试试这个:

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。

尝试以下方法:

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。

您可以将代码简化如下:

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


您可以将代码简化如下:

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


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

name_list = ["Kate", "David"]

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

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

name_list = ["Kate", "David"]

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

那么,你的实际问题是什么?XPath不正确,或者第页缺少列表中包含文本的某些元素?@Andersson,先生,元素在那里。问题是XPath不正确。那么您的实际问题是什么?XPath不正确,或者第页缺少列表中包含文本的某些元素?@Andersson,先生,元素在那里。问题不正确。谢谢你,先生。我喜欢它的表达方式,但不明白为什么当我把它写进台词时它就不起作用了。那是因为时间问题。您可以实现(最好)或在每次迭代后添加
time.sleep(timeout)
,谢谢。我喜欢它的表达方式,但不明白为什么当我把它写进台词时它就不起作用了。那是因为时间问题。您可以实现(最好)或在每次迭代后添加
time.sleep(timeout)
,谢谢!这是一条简单的线,但它是唯一有效的。(原来我觉得学习不太好:)谢谢!这是一条简单的线,但它是唯一有效的。(起初我认为这对学习不太好:)