gpt4 book ai didi

python - lxml 经典 : Get text content except for that of nested tags?

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:20 25 4
gpt4 key购买 nike

这一定是绝对的经典,但我在这里找不到答案。我正在使用 lxml cssselect 解析以下标记:

<li><a href="/stations/1"><span class="num">3</span> Detroit</a></li>

我想获取<li>的内容标记没有 <span> 的内容标签。

目前我有:

stop_list = doc.cssselect('ol#stations li a')
start = stop_list[0].text_content().strip()

但这给了我 3 Detroit .我怎样才能得到 Detroit

最佳答案

对于您的示例,我认为使用 XPath 比使用 CSS 更简洁、更容易:

>>> xml = '<li><a href="/stations/1"><span class="num">3</span> Detroit</a></li>'
>>> root = etree.fromstring(xml)
>>> print( root.xpath('/li/a/text()'))
[' Detroit']

>>> xml = '<li><a href="/stations/1">I <span>FooBar!</span> love <span class="num">3</span> Detroit</a></li>'
>>> root = etree.fromstring(xml)
>>> print( root.xpath('/li/a/text()'))
['I ', ' love ', ' Detroit']

>>> ' '.join([x.strip() for x in root.xpath('/li/a/text()')])
'I love Detroit'

关于python - lxml 经典 : Get text content except for that of nested tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com