我想查询一个html字符串,并将超链接中的href属性和文本节点提取到列表(或任何其他字典)中。从Xpath查询获取属性和文本作为列表
考虑下面的代码:
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 :) – madflow 2014-09-13 18:57:21