首页 > 解决方案 > 防止 BeautifulSoup 的 find_all() 转换转义的 html 标签

问题描述

我有一些文字:

text = <p>&lt;b&gt;test&lt;/b&gt;<br/></p>

我用漂亮的汤读到的 4

soup = BeautifulSoup(text, "html.parser") # soup: <p>&lt;b&gt;test&lt;/b&gt;<br/></p>

然后我想获取文本节点:

text_nodes = soup.find_all(text=True)

但转义的 HTML 在此过程中未转义:text_nodes: ['<b>test</b>']

如何防止find_all()step 转换我的转义 HTML 标签?

标签: python-3.xbeautifulsoupescaping

解决方案


text=True认为没有选择保持字符串不变。

我的解决方案就是用循环转义结果

from bs4 import BeautifulSoup
from html import escape

text = '<p>&lt;b&gt;test&lt;/b&gt;<br/></p>'
soup = BeautifulSoup(text, "html.parser")
text_nodes = [escape(x) for x in soup.strings]
print(text_nodes)
# ['&lt;b&gt;test&lt;/b&gt;']

soup.strings是 的较短版本soup.find_all(text=True)


推荐阅读