Python/Etree:从元素及其子元素获取文本
我必须使用这样的 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>
问题是我需要从子级(如 a
s 和 i
s)和文本节点(如子节点之间的 ,
部分)。
我所能做的就是从每个孩子那里获取文本并将其放在一起(这给了我除了所有文本节点之外的所有内容)或者仅获取文本节点(而不是 a
和 i
s)。有没有办法同时获得两者?
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 a
s and i
s) 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 i
s). Is there a way to get both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.您可以使用 lxml.html 来完成此操作。
You can do this using lxml.html.