Skip to main content
 首页 » 编程设计

python之在 python 中避免 UnicodeEncodeError

2025年05月04日13hnrainll

我试图解析一个 html table使用带有以下脚本的 python 转换为 csv:

from bs4 import BeautifulSoup 
import requests 
import csv 
 
 
csvFile = open('log.csv', 'w', newline='') 
writer = csv.writer(csvFile) 
def parse(): 
    html = requests.get('https://en.wikipedia.org/wiki/Comparison_of_text_editors') 
    bs = BeautifulSoup(html.text, 'lxml') 
    table = bs.select_one('table.wikitable') 
    rows = table.select('tr') 
    for row in rows: 
        csvRow = [] 
        for cell in row.findAll(['th', 'td']): 
            csvRow.append(cell.getText()) 
        writer.writerow(csvRow) 
        print(csvRow) 
 
 
parse() 
csvFile.close() 

此代码输出格式清晰的 CSV 文件,没有编码问题。 在 Enrico Tröger 的 Geany 之前一切都很好。我的脚本无法写入 ö 到一个csv文件中,所以我试过这个: csvRow.append(cell.text.encode('ascii', 'replace')) 而不是:csvRow.append(cell.getText()) 一切都很好,尽管每个表格单元格都嵌套在 b'' 中。 那么,我怎样才能得到一个没有编码问题的清晰格式的 csv 文件(如第一个屏幕截图中所示)并替换或忽略所有 使用我的 scipt 的非 unicode 符号(如第二个屏幕截图中所示)?

请您参考如下方法:

改变这个:

csvFile = open('log.csv', 'w', newline='') 

给这个:

csvFile = open('log.csv', 'w', newline='', encoding='utf8') 

csv module documentation :

Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:

import csv 
with open('some.csv', newline='', encoding='utf-8') as f: 
    reader = csv.reader(f) 
    for row in reader: 
         print(row) 

The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.

我想你的系统默认编码不是utf8。 你可以这样检查:

import locale 
locale.getpreferredencoding() 

希望对您有所帮助!