【发布时间】:2018-07-18 18:31:06
【问题描述】:
我编写了一个脚本来抓取 YouTube 播放列表页面的标题
根据打印语句,一切正常,直到我尝试将标题写入文本文件,此时我得到“UnicodeEncodeError: 'charmap' codec can't encode characters in position...”
我尝试在打开文件时添加“encoding='utf8'”,虽然这修复了错误,但所有中文字符都被随机的乱码替换
我还尝试使用“替换”对输出字符串进行编码,然后对其进行解码,但这也只是将所有特殊字符替换为问号
这是我的代码:
from bs4 import BeautifulSoup as BS
import urllib.request
import re
playlist_url = input("gib nem: ")
with urllib.request.urlopen(playlist_url) as response:
playlist = response.read().decode('utf-8')
soup = BS(playlist, "lxml")
title_attrs = soup.find_all(attrs={"data-title":re.compile(r".*")})
titles = [tag["data-title"] for tag in title_attrs]
titles_str = '\n'.join(titles)#.encode('cp1252','replace').decode('cp1252')
print(titles_str)
with open("playListNames.txt", "a") as f:
f.write(titles_str)
这是我用来测试的示例播放列表: https://www.youtube.com/playlist?list=PL3oW2tjiIxvSk0WKXaEiDY78KKbKghOOo
【问题讨论】:
-
您确定这些乱码不是由于您的编辑器/您使用什么来显示结果吗?
-
我只是将此代码复制到一个文件中,并使用给出的 URL 运行它而没有错误。我会向您展示一些输出,但我遇到了复制和粘贴问题,抱歉。您是否有机会在 Python 2 下运行此代码?
-
@ArneRecknagel 我不这么认为;我正在使用 Sublime Text 2
-
@holdenweb 这很奇怪;我正在使用 Spyder IDE 在 Python 3 下运行代码
-
您正在附加到
playListNames.txt。你确定文件的编码是UTF吗?您是否尝试过creating a new file open("playListNames_new.txt", "w")(可能还设置了编码)?
标签: python html python-3.x unicode fwrite