python-3.x - 防止 BeautifulSoup 的 find_all() 转换转义的 html 标签
问题描述
我有一些文字:
text = <p><b>test</b><br/></p>
我用漂亮的汤读到的 4:
soup = BeautifulSoup(text, "html.parser") # soup: <p><b>test</b><br/></p>
然后我想获取文本节点:
text_nodes = soup.find_all(text=True)
但转义的 HTML 在此过程中未转义:text_nodes: ['<b>test</b>']
如何防止find_all()
step 转换我的转义 HTML 标签?
解决方案
我text=True
认为没有选择保持字符串不变。
我的解决方案就是用循环转义结果
from bs4 import BeautifulSoup
from html import escape
text = '<p><b>test</b><br/></p>'
soup = BeautifulSoup(text, "html.parser")
text_nodes = [escape(x) for x in soup.strings]
print(text_nodes)
# ['<b>test</b>']
soup.strings
是 的较短版本soup.find_all(text=True)
。
推荐阅读
- aws-cognito - Google 使用 aws cognito 用户池登录到 vuejs 应用程序
- javascript - 如何为两个连接的字符串分配值和范围
- intellij-idea - 如何在打开驼峰的情况下在 Pycharm 中选择整个“camelCaseWord”
- java - Spring Boot 数据库初始化只有一次
- javascript - 从 Angular 5 下载 spring boot rest services 的文件
- angularjs - 使用角度方式删除行时,角度数据表消失
- datetime - 在 ElasticSearch 中以微秒格式保存日期
- python - Is there any way to make a timeseries scatterplot with array sizing in Matplotlib?
- ios - 聊天信使 UITableViewCell,正在加载消息
- python-3.x - 多处理中的 Google Stackdriver 不起作用