解析lxml中的HTML树:如何检索元素中的文本?

2024-04-26 01:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在元素中检索正确的文本。输出如下:

(Pdb) p etree.tostring(els[0])
'<h5 class="msg-delivered" style="padding:0;text-rendering:optimizeLegibility;line-height:1.1;margin-bottom:15px;-webkit-font-smoothing:antialiased;font-family:&quot;Open Sans&quot;, &quot;Helvetica Neue&quot;, Arial, Helvetica, sans-serif;color:#888888;vertical-align:middle;margin:0;font-size:13px;font-weight:300 !important">&#13;\n<i class="ic-icon-delivered" style="margin:0;padding:0;font-family:&quot;Open Sans&quot;, &quot;Helvetica Neue&quot;, &quot;Helvetica&quot;, Helvetica, Arial, sans-serif;text-rendering:optimizeLegibility;position:relative;background:url(https://d1s8987jlndkbs.cloudfront.net/assets/sprite-ratings-ee0696744f54df6536179c70e24217e3.png) no-repeat -12px -12px;background-size:132px 436px;display:none;vertical-align:middle;width:25px;height:25px;background-position:-16px -16px;top:0"/>&#13;\nYour order was delivered&#13;\non&#13;\n6/4&#13;\n@&#13;\n4:44 PM&#13;\n</h5>&#13;\n'
(Pdb) p els[0].text
'\r\n'

我怎样才能得到字符串:“你的物品是6/4下午4:40送达的”?我可以在etree.tostring()输出,但想知道els[0].text选项为何不起作用?在


Tags: textmarginstylepdbclassetreeh5background
2条回答

您可以尝试使用xpath函数string(),该函数返回当前元素中所有文本节点的串联值:

import lxml.html
html = """<h5 class="msg-delivered" style="padding:0;text-rendering:optimizeLegibility;line-height:1.1;margin-bottom:15px;-webkit-font-smoothing:antialiased;font-family:&quot;Open Sans&quot;, &quot;Helvetica Neue&quot;, Arial, Helvetica, sans-serif;color:#888888;vertical-align:middle;margin:0;font-size:13px;font-weight:300 !important">&#13;\n<i class="ic-icon-delivered" style="margin:0;padding:0;font-family:&quot;Open Sans&quot;, &quot;Helvetica Neue&quot;, &quot;Helvetica&quot;, Helvetica, Arial, sans-serif;text-rendering:optimizeLegibility;position:relative;background:url(https://d1s8987jlndkbs.cloudfront.net/assets/sprite-ratings-ee0696744f54df6536179c70e24217e3.png) no-repeat -12px -12px;background-size:132px 436px;display:none;vertical-align:middle;width:25px;height:25px;background-position:-16px -16px;top:0"/>&#13;\nYour order was delivered&#13;\non&#13;\n6/4&#13;\n@&#13;\n4:44 PM&#13;\n</h5>"""
tree = lxml.html.etee.fromstring(html)
print(tree.xpath("string()"))

输出:

^{pr2}$

如果需要所有文本,只需使用:

els[0].text_content()

也就是说,假设您在html中加载了:

^{pr2}$

请注意,您可能希望避免lxml.html.etree.fromstring,只需使用lxml.html.fromstring

相关问题 更多 >