Python 3.x Python-在本地.html文件上美化SOUP4 prettify()时丢失CSS格式

Python 3.x Python-在本地.html文件上美化SOUP4 prettify()时丢失CSS格式,python-3.x,encoding,beautifulsoup,prettify,Python 3.x,Encoding,Beautifulsoup,Prettify,我需要用Beautifulsoup4编辑数百个.html文件 当我将更改写回文件时,我的CSS格式将丢失 在美化()之前: 和美化(): 我的代码: from bs4 import BeautifulSoup import os files = [] path = r"C:\Files" for file in os.listdir(path): if file.endswith('.html'): files.append(file) for htmlfile

我需要用Beautifulsoup4编辑数百个.html文件

当我将更改写回文件时,我的CSS格式将丢失

美化()之前

美化()

我的代码:

from bs4 import BeautifulSoup
import os

files = []
path = r"C:\Files"

for file in os.listdir(path):
    if file.endswith('.html'):
        files.append(file)

for htmlfile in files:
    soup = BeautifulSoup(open(htmlfile, encoding="utf-8"), "html.parser")

    soup.header.decompose()
    soup.menu.decompose()

    pretty_html = soup.prettify('utf-8', 'minimal')
    with open(htmlfile, "wb") as outfile:
        outfile.write(pretty_html)
如果我不
prettify()
并写出如下内容:

with open(file, "w") as outfile:
    outfile.write(str(soup))
我得到一个编码错误:

outfile.write(str(soup))
File "...env\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2192' in position 2027: character maps to <undefined>
outfile.write(str(soup))
文件“…env\lib\encodings\cp1252.py”,第19行,编码
返回codecs.charmap\u encode(输入、自身错误、编码表)[0]
UnicodeEncodeError:“charmap”编解码器无法对位置2027中的字符“\u2192”进行编码:字符映射到
似乎是“utf-8”到“cp1252”的对应问题


我无法理解这种编码方式。

您可以使用文件所在的正确编码创建一个soup实例。此外,您可能不需要打开文件以二进制模式写入。或者您是否希望将存储的标记转换为
utf-8
编码?文件采用utf-8编码,我也在为soup实例采用utf-8编码。还尝试了在不打开二进制格式的情况下写入,仍然会出现编码错误,请参阅操作的后面部分。好的,尝试在没有格式化程序的情况下调用prettify,例如
soup.prettify(formatter=None)
。这将防止字符串被修改。将输出文件写入示例url,尝试通过beautifulsoup将其保存到.html,代码段
中的CSS格式将全部丢失