python - 将结果从 python 写入 csv 文件 [UnicodeEncodeError : 'charmap' codec can't encode character

标签 python python-3.x csv character-encoding python-unicode

我一直在尝试编写一个脚本,该脚本可能会从定义的 YouTube 视频的评论部分中删除用户名列表,并将这些用户名粘贴到 .csv 文件中。

这是脚本:

from selenium import webdriver
import time
import csv
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as soup
driver=webdriver.Chrome()
driver.get('https://www.youtube.com/watch?v=VIDEOURL')
time.sleep(5)
driver.execute_script("window.scrollTo(0, 500)")
time.sleep(3)
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)
time.sleep(5)
scroll_time = 40
for num in range(0, scroll_time):
    html.send_keys(Keys.PAGE_DOWN)
for elem in driver.find_elements_by_xpath('//span[@class="style-scope ytd-comment-renderer"]'):
    print(elem.text)
    with open('usernames.csv', 'w') as f:
        p = csv.writer(f)
        p.writerows(str(elem.text));

它不断抛出第 19 行的错误:
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u30b9' in position 0: character maps to <undefined>

我在这里读到这可能与 Windows 控制台处理 unicode 的方式有关,并看到了有关下载和安装 unicode 库包的潜在解决方案,但这也无济于事。

谁能帮我弄清楚我做错了什么?

附注。我正在使用最新版本的 python (3.7)。

非常感激,
谢尔盖。

最佳答案

Python 3 str写入磁盘时,值需要编码为字节。如果没有为文件指定编码,Python 将使用平台默认值。在这种情况下,默认编码无法编码 '\u0389',因此引发 UnicodeEncodeError .
解决方法是在打开文件时指定编码为UTF-8:

with open('usernames.csv', 'w', encoding='utf-8') as f:
    p = csv.writer(f)
    ...
由于 UTF-8 不是您平台的默认编码,因此在打开文件时,您还需要在 Python 代码或 Excel 等应用程序中指定编码。
Windows 支持 UTF-8 的修改版本,在 Python 中名为“utf-8-sig”。此编码在文件开头插入三个字符,以向 Windows 应用程序标识该文件的编码,否则这些应用程序可能会尝试使用 8 位编码进行解码。如果该文件将专门在 Windows 机器上使用,那么使用这种编码可能是值得的。
with open('usernames.csv', 'w', encoding='utf-8-sig') as f:
    p = csv.writer(f)
    ...

关于python - 将结果从 python 写入 csv 文件 [UnicodeEncodeError : 'charmap' codec can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52658773/

相关文章:

python - 在python中获取类中的所有常量

python - 并行运行 Python 脚本并等待所有脚本完成,然后再执行更多并行脚本

python -\n 在 python 中的工作

php - 仅在某些行之间将 csv 导入到 mysql

bash - 添加尾随逗号以确保 .csv 行具有相同的列数

python - 如何使用 networkx 反转有向图中的箭头?

Python 子进程 stdout.readlines() 卡住了

python - Python3中中断的shell

python - 预期 Python 中的预期 block

perl - 使用 Perl 打开在 Mac Excel 中创建的 CSV 文件