繁体   English   中英

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

[英]How to convert UTF-8 list to String in python

我需要将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>

如果也要以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) 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM