如何在Python中将UTF-8列表转换为字符串

时间:2019-05-07 07:40:58

标签: python python-3.x utf-8

我需要将BeautifulSoup结果保存到.txt文件中。而且我需要使用str()将结果转换为字符串,并且由于列表为UTF-8而无法正常工作:

# -*- coding: utf-8 -*-

page_content = soup(page.content, "lxml")

links = page_content.select('h3', class_="LC20lb")

for link in links:
    with open("results.txt", 'a') as file:
        file.write(str(link) + "\n")

并得到此错误:

  File "C:\Users\omido\AppData\Local\Programs\Python\Python37-32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 183-186: character maps to <undefined>

1 个答案:

答案 0 :(得分:1)

如果您还想以UTF-8格式写入文件,则需要指定以下内容:

with open("results.txt", 'a', encoding='utf-8') as file:
    file.write(str(link) + "\n")

最好只打开一次文件:

with open("results.txt", 'a', encoding='utf-8') as file:
    for link in links:
        file.write(str(link) + "\n")

(您也可以print(link, file=file)。)