【问题标题】:Python Selenium: How to get elements from multiple html lists of undefined length that have the same relative xpath?Python Selenium:如何从具有相同相对 xpath 的多个未定义长度的 html 列表中获取元素?
【发布时间】:2021-12-15 19:54:19
【问题描述】:

我正在抓取一个页面,我正在寻找以下列表中的所有元素:

description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1/text()='Values']/ul[@class='bullet-list']")

但给定页面上的数量未知,主要在 3-10 之间。每个列表中还有未知数量的项目(每个列表中的项目数不匹配)。如果我这样搜索列表项:

description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1/text()='Values']/ul[@class='bullet-list']/li")

我得到了所有列表项,但现在我不知道它们属于哪个列表。

我想做的是这样的

description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1/text()='Values']/ul[@class='bullet-list']")
for x in range(len(description)):
    values = driver.find_elements(By.XPATH, f"{description[x].xpath}/li")
    for y in values:
        b_list.append(y.text)
    a_list.append(b_list)

所以你可以明白为什么我需要知道这些项目来自哪个列表,以便它们可以在同一个 [] 中。

我可以使用绝对 xpath 来解决这个问题,但如果我能找到使用相对 xpath 的方法会更好。

【问题讨论】:

    标签: python html selenium xpath


    【解决方案1】:

    如果您想从多个列表中获取项目,您可以尝试

    lists = []
    description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1='Values']/ul[@class='bullet-list']")
    for _list in description:
        lists.append([li.text for li in _list.find_elements(By.XPATH, './li')])
    print(lists)
    

    【讨论】:

    • 谢谢你成功了,我之前尝试过相同的解决方案,但是对于 xpath,我使用了 '/li' 而不是 './li',它没有产生任何结果,所以我认为这个解决方案没用。谢谢!
    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多