【问题标题】:Get attributes and text from Xpath query as a list从 Xpath 查询中获取属性和文本作为列表
【发布时间】:2014-09-13 18:34:04
【问题描述】:

我想查询一个 html 字符串并将超链接中的 href 属性和文本节点提取到列表(或任何其他字典)中。

考虑以下代码:

from lxml import html
str = '<a href="href1"> Text1 </a>' \
      '<a href="href2"> Text2 </a>' \
      '<a href="href3"> Text3 </a>'
tree = html.fromstring(str)
items = tree.xpath('//a')

values = list()
for item in items:
    text = item.text
    href = item.get('href')
    values.append((text, href))

for text, href in values:
    print text, href

这行得通!

我想知道是否可以省略 for item in items: 循环并仅通过 XPath 查询获得 values 列表。

tree.xpath('//a/text()')tree.xpath('//a/@href') 给我一个 - 但我想要一个列表中的两个值。

【问题讨论】:

    标签: python xpath lxml


    【解决方案1】:

    您可以使用| 来构建复合XPath。文本和 href 都将在一个列表中返回,items。您可以使用grouper recipezip(*[iterable]*2) 将每两个项目配对。 (但是请注意,这依赖于交替的 href 和文本字符串):

    from lxml import html
    str = '<a href="href1"> Text1 </a>' \
          '<a href="href2"> Text2 </a>' \
          '<a href="href3"> Text3 </a>'
    tree = html.fromstring(str)
    items = tree.xpath('//a/text() | //a/@href')
    
    for href, text in zip(*[iter(items)]*2):
        print text, href
    

    产量

     Text1  href1
     Text2  href2
     Text3  href3
    

    【讨论】:

      【解决方案2】:

      你可以使用zip:

      a = [1, 2, 3]
      b = ['a', 'b', 'c']
      zip(a, b) # [(1, 'a'), (2, 'b'), (3, 'c')]
      

      所以根据你的 xpath 表达式:

      texts = tree.xpath('//a/text()')
      hrefs = tree.xpath('//a/@href')
      values = zip(texts, hrefs)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        相关资源
        最近更新 更多