【问题标题】:Loop over list of elements for find_element_by_xpath() by Selenium and WebdriverSelenium 和 Webdriver 循环遍历 find_element_by_xpath() 的元素列表
【发布时间】:2018-07-09 07:37:02
【问题描述】:

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

打印 xpath 的输出看起来不错,但是 selenium 说:

common.exceptions.NoSuchElementException

【问题讨论】:

  • 那么您的实际问题是什么?页面上缺少不正确的 XPath 或列表中包含文本的某些元素?
  • @Andersson,先生,元素就在那里。问题是 XPath 不正确。

标签: python selenium selenium-webdriver xpath


【解决方案1】:

您可以将代码简化如下:

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)

【讨论】:

  • 谢谢您,先生。我喜欢它的表达方式,但不明白为什么当我把它放到台词中时它不起作用。
  • 那是因为时间问题。您可以实现ExplicitWait(首选)或在每次迭代后简单地添加time.sleep(timeout)
【解决方案2】:

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

name_list = ["Kate", "David"]

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

【讨论】:

    【解决方案3】:

    试试这个:

    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。

    【讨论】:

    • 谢谢!这是一条简单的线,但它是唯一有效的。 (最初我认为它不适合学习:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2020-02-17
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多