使用BeautifulSoup处理前标记中的尖括号 [英] Handle angle bracket in pre tag using BeautifulSoup

查看:38
本文介绍了使用BeautifulSoup处理前标记中的尖括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串

html = "<pre>City_<cityname>_001</pre>"

尝试使用BeautifulSoup 4解析时,使用以下代码

>>> from bs4 import BeautifulSoup
>>> html = "<pre>City_<cityname>_001</pre>"
>>> soup = BeautifulSoup(html, "html.parser")
>>> soup
<pre>City_<cityname>_001</cityname></pre>
>>> soup.text
City__001

可以看到,BeautifulSoup将cityname视为新标签。

有没有什么方法可以避免这种情况,以获取正确的文本和html?

推荐答案

注释被解析器忽略。您可以在分析前将<pre>的内容设为注释,然后再将extract()设为注释。

import bs4
html = "<pre>City_<cityname>_001</pre>"
soup = bs4.BeautifulSoup(html.replace("<pre>","<pre><!--").replace("</pre>","--></pre>"), "lxml")
pre=soup.find('pre')
pre_comment=pre.find(text=lambda text: isinstance(text, bs4.Comment)).extract()
print(pre_comment)

输出:

City_<cityname>_001

这篇关于使用BeautifulSoup处理前标记中的尖括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆