【问题标题】:Encoding error trying to write file with python尝试使用 python 写入文件的编码错误
【发布时间】:2018-05-09 16:53:31
【问题描述】:

这是完整的脚本:

import requests
import bs4


res = requests.get('https://example.com')
soup = bs4.BeautifulSoup(res.text, 'lxml')
page_HTML_code = soup.prettify()

multiline_code = """{}""".format(page_HTML_code)

f = open("testfile.txt","w+")
f.write(multiline_code)
f.close()

所以我试图将整个下载的 HTML 写成一个文件,同时保持它的整洁。

我知道它的文本存在问题并且无法保存某些字符,但我不确定如何正确编码文本。

有人可以帮忙吗?

这是我将收到的错误消息

"C:\Location", line 16, in <module>
    f.write(multiline_code)
  File "C:\\Anaconda3\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 '\u0421' in position 209: character maps to <undefined>

【问题讨论】:

  • 尝试将open('testfile.txt', 'wb') 写入二进制文件。要读取文件,您需要使用open('testfile.txt', 'rb') 打开它。
  • 另外,使用with open('testfile.txt', 'wb') as a_file: 后跟缩进的a_file.write(...),而不是使用显式的openclose 语句。上下文管理器(with ... as ...: 语法)出错的可能性较小。
  • 您可以尝试使用.encode('utf-8') 进行编码,尽管我认为您可能会遇到同样的问题。您还可以选择忽略 .encode('utf-8', errors='ignore') or one of several other options listed here 的错误。
  • 例如,我认为.encode('utf-8', errors='backslashreplace') 可能会用文字字符串'\u0421' 替换未知字符,因此您不会丢失该信息,但您可能需要做一些时髦的事情来解码它你读回来了。
  • @Engineero 感谢您的帮助。 :) 刚刚发布了我自己的问题的答案。

标签: python-3.x encoding


【解决方案1】:

我做了一些挖掘,这很有效:

import requests
import bs4


res = requests.get('https://example.com')

soup = bs4.BeautifulSoup(res.text, 'lxml')

page_HTML_code = soup.prettify()



multiline_code = """{}""".format(page_HTML_code)

#add the Encoding part when opening file and this did the trick
with open('testfile.html', 'w+', encoding='utf-8') as fb:
    fb.write(multiline_code)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多