python - 在 Python 2.7 上使用 xpath 提取 href 值

标签 python html xpath

我有这个 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/

相关文章:

python - 使用XCom在类之间交换数据?

html - DIV 中的 UL 不会更新高度

从集合中获取字典的 Pythonic 方法

python - Flask-SQLAlchemy 检查表中是否存在行

Javascript - 是否可以有 3 个“if”变量或者这是一个错误?

java - 如何使用 UIAutomation 谓词查找 UIATableView 子元素?

xslt - 如何在 XSLT 中进行字符串操作?

python - 如何使用 Selenium WebDriver 和 Python 提取元素中的文本?

python - `cimport numpy` 使用 Cython 引发错误

html - Bootstrap 绝对定位的 div 在导航栏上方未正确显示