首页 > 解决方案 > 我想将 bs4 beautifulSoup 对象中的 HTML 实体(十六进制)保存到文件中

问题描述

问题

from bs4 import BeautifulSoup
a=BeautifulSoup('<p class="t5">&#x20b9; 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> 这就是问题所在,&#x20b9;当我们将 bs4 对象更改为 str 时不会发生这种情况,但是当我们将其写入文件时会发生这种情况。

我试过什么

  1. 将 HTML 实体转换为 Unicode 字符串
  2. 如何将 bs4.element.ResultSet 转换为字符串?Python
  3. 在 Python 中将金额转换为印度表示法
  4. 如何在 Python 3.1 中对字符串中的 HTML 实体进行转义?

有什么解决办法

将 BeautifulSoup 对象转换为字符串而不更改 & #x20b9; 登录 ₹ (顺便说一下 str() 方法)。然后将字符串保存到文件中。

标签: pythonhtmlbeautifulsoup

解决方案


encoding='utf-8'存档使用

前任:

from bs4 import BeautifulSoup

a=BeautifulSoup('<p class="t5">&#x20b9; 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>

推荐阅读