在python 2.7上使用xpath提取href值

tcp*_*008 4 python xpath

快速简单:

<a href="some content">Click here</a>
Run Code Online (Sandbox Code Playgroud)

如何在python上使用xpath提取“某些内容”并“单击我”?

到目前为止,我有以下内容(仅从href结果中提取“某些内容”):

import lxml.etree as LE
import requests

r = requests.get("http://localhost")
html = r.text
root = LH.fromstring(html)
print root.xpath('//a/@href')
Run Code Online (Sandbox Code Playgroud)

非常感谢。

unu*_*tbu 5

您只能使用XPath来选择一个或另一个,但是您可以选择所有<a>元素,然后选择href属性和文本内容,如下所示:

for elt in root.xpath('//a'):
    print(elt.attrib['href'], elt.text_content())
Run Code Online (Sandbox Code Playgroud)