【问题标题】:get text from html using lxml使用 lxml 从 html 获取文本
【发布时间】:2015-01-05 07:25:56
【问题描述】:

我正在尝试使用来自 lxml 的 Xpath 从该站点获取名人姓名列表,但遇到了问题。

这里是 HTML

<div class="lists">
            <dl> <dt>A</dt> <dd><a href="/people/adam_levine/" id="20608779">Adam Levine</a>    </dd>

我想得到文本 Adam Levine

我在 python 中的代码是...

celebs = tree.xpath('//dd[a]/following-sibling::node()')

但我的结果是 Element dd at 0x1084ad4c8>...

如果有人可以提供帮助,那就太好了。谢谢

【问题讨论】:

  • 尝试在 celebs = tree.xpath() 之后添加 print(celebs.text)

标签: python html html-parsing lxml


【解决方案1】:

使用text() 提取文本,而不是following-sibling::node(),如下所示:

from lxml import etree

# your HTML is invalid, I have purposefully put the </dl> and </div> closing tags
s = '''<div class="lists">
            <dl> <dt>A</dt> <dd><a href="/people/adam_levine/" id="20608779">Adam Levine</a>    </dd></dl></div>'''

tree = etree.fromstring(s)

tree.xpath('.//dd/a/text()')
['Adam Levine']

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2021-04-06
    • 1970-01-01
    • 2013-08-25
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多