【发布时间】: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') 给我一个 - 但我想要一个列表中的两个值。
【问题讨论】: