如何在python中将UTF-8列表转换为字符串
我需要将BeautifulSoup结果保存到如何在python中将UTF-8列表转换为字符串,python,python-3.x,utf-8,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:
.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>
文件“C:\Users\omido\AppData\Local\Programs\Python\Python37-32\lib\encodings\cp1252.py”,编码中的第19行
返回codecs.charmap\u encode(输入、自身错误、编码表)[0]
UnicodeEncodeError:“charmap”编解码器无法对位置183-186中的字符进行编码:字符映射到
如果您也想以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")
(您也可以打印(链接,file=file)
)