我想查詢一個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