python - 我想将 bs4 beautifulSoup 对象中的 HTML 实体(十六进制)保存到文件中
问题描述
问题
from bs4 import BeautifulSoup
a=BeautifulSoup('<p class="t5">₹ 10,000 or $ 133.46</p>')
b=open('file.html','w')
b.write(str(a))
结果是
UnicodeEncodeError: 'charmap' codec can't encode character '\u20b9' in position 19038: character maps to <undefined>
这就是问题所在,₹
当我们将 bs4 对象更改为 str 时不会发生这种情况,但是当我们将其写入文件时会发生这种情况。
我试过什么
- 将 HTML 实体转换为 Unicode 字符串
- 如何将 bs4.element.ResultSet 转换为字符串?Python
- 在 Python 中将金额转换为印度表示法
- 如何在 Python 3.1 中对字符串中的 HTML 实体进行转义?
有什么解决办法
将 BeautifulSoup 对象转换为字符串而不更改 & #x20b9; 登录 ₹ (顺便说一下 str() 方法)。然后将字符串保存到文件中。解决方案
encoding='utf-8'
存档使用
前任:
from bs4 import BeautifulSoup
a=BeautifulSoup('<p class="t5">₹ 10,000 or $ 133.46</p>')
with open(filename,'w', encoding='utf-8') as infile:
infile.write(str(a)) # OR infile.write(a.prettify())
输出:
<p class="t5">₹ 10,000 or $ 133.46</p>
推荐阅读
- android - ExoPlayer 无法播放 RTMP 语音流
- momentjs - 如何使用momentjs找到给定月份的任何周六/周日?
- sql - 根据日期差异进行选择
- sharepoint-online - 为什么超过次要版本限制时,SharePoint Online 会删除最新的而不是最旧的次要版本?
- angular7 - 使用 Angular 2+ 在页面顶部显示所选内容
- html - Bootstrap 4.3 使导航栏在页面顶部静态且透明
- javascript - Angular 8 - 在另一个组件中复制选择值
- python - 使用 matplotlib 创建详细的 svg 图
- sql - SQL:当另一行中的值更改时增加一行
- ios - React Native / Expo iOs - 网络请求因我的 Api 上的 Fetch 而失败