Python/Etree:从元素及其子元素获取文本

发布于 2024-11-09 01:32:54 字数 635 浏览 0 评论 0原文

我必须使用这样的 HTML:

<li><a href="#">S:</a><a class="#"> (n) </a><a href="#">trial</a>, <a href="#">trial run</a>, <b>test</b>, <a href="#">tryout</a> (trying something to find out about it) <i>"a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"</i></li>

问题是我需要从子级(如 as 和 is)和文本节点(如子节点之间的 , 部分)。

我所能做的就是从每个孩子那里获取文本并将其放在一起(这给了我除了所有文本节点之外的所有内容)或者仅获取文本节点(而不是 ais)。有没有办法同时获得两者?

I've got to use some HTML like this:

<li><a href="#">S:</a><a class="#"> (n) </a><a href="#">trial</a>, <a href="#">trial run</a>, <b>test</b>, <a href="#">tryout</a> (trying something to find out about it) <i>"a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"</i></li>

The problem is that I need to get the text from both the children (like the as and is) and the text nodes (like the , parts between children).

All I'm able to do is get the text from each child and put it together (which gives me everything but all the text nodes) OR get the just the text nodes (and not the a and is). Is there a way to get both?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一直都在从未离去 2024-11-16 01:32:54

lxml 变更日志 显示 lxml v2.3 与 python 3.1.2 及更高版本兼容。

您也可以使用正则表达式 re.sub(r'<[^>]*?>', '', val) 作为 Python相当于PHP的strip_tags说的。

The lxml changelog shows lxml v2.3 is compatible with python 3.1.2 and newer.

Also you could use regexp re.sub(r'<[^>]*?>', '', val) as Python's equivalent to PHP's strip_tags said.

睫毛上残留的泪 2024-11-16 01:32:54

您可以使用 lxml.html 来完成此操作。

In [1]: import lxml.html

In [2]: el = lxml.html.fromstring('<li><a href="#">S:</a><a class="#"> (n) </a><a href="#">trial</a>, <a href="#">trial run</a>, <b>test</b>, <a href="#">tryout</a> (trying something to find out about it) <i>"a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"</i></li>')

In [3]: print el.text_content()
S: (n) trial, trial run, test, tryout (trying something to find out about it) "a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"

You can do this using lxml.html.

In [1]: import lxml.html

In [2]: el = lxml.html.fromstring('<li><a href="#">S:</a><a class="#"> (n) </a><a href="#">trial</a>, <a href="#">trial run</a>, <b>test</b>, <a href="#">tryout</a> (trying something to find out about it) <i>"a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"</i></li>')

In [3]: print el.text_content()
S: (n) trial, trial run, test, tryout (trying something to find out about it) "a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文