我有这个 HTML:
<a href="some content">Click here</a>
如何在 Python 2.7 上使用 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')
最佳答案
您只能使用 XPath 选择一个或另一个,但您可以选择所有 <a>
元素然后摘掉href
属性和文本内容如下:
for elt in root.xpath('//a'):
print(elt.attrib['href'], elt.text_content())
关于python - 在 Python 2.7 上使用 xpath 提取 href 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15272087/