Skip to main content
 首页 » 编程设计

python之Python 3.4 中的 YouTube API UnicodeEncodeError

2024年10月24日12落叶无声

我在探索 YouTube 数据 API 时发现编码不当的结果阻碍了我。在检索到标题中包含未映射字符的集合之前,我得到了很好的结果。我的代码现在是(为你们好人清理了一点):

import urllib.request 
import urllib.parse 
import json 
import datetime 
 
# Look for videos published up to THIS MANY hours ago 
IntHoursToSub = 2 
RightNow = datetime.datetime.utcnow() 
StartedAgo = datetime.timedelta(hours=-(IntHoursToSub)) 
HourAgo = RightNow + StartedAgo 
HourAgo = str(HourAgo).replace(" ", "T") 
HourAgo = HourAgo[:HourAgo.find(".")] + "Z" 
 
# Get API Key from your safe place and set up the API link 
YouTubeAPIKey = open('YouTubeAPIKey.txt', 'r').read() 
locuURL = "https://www.googleapis.com/youtube/v3/search" 
values = {"key": YouTubeAPIKey, 
          "part": "snippet", 
          "publishedAfter": HourAgo, 
          "relevanceLanguage": "en", 
          "regionCode": "us", 
          "maxResults": "50", 
          "type": "live"} 
postData = urllib.parse.urlencode(values) 
fullURL = locuURL + "?" + postData 
 
# Set up response holder and handle exceptions 
respData = "" 
try: 
    req = urllib.request.Request(fullURL) 
    respData = urllib.request.urlopen(req).read().decode() 
except Exception as e: 
    print(str(e)) 
#print(respData) 
 
# Read JSON response and iterate through for video names/URLs 
jsonData = json.loads(respData) 
for object in jsonData["items"]: 
    if object["id"]["kind"] == "youtube#video": 
        print(object["snippet"]["title"], "https://www.youtube.com/watch?v=" + object["id"]["videoId"]) 

错误是:

Traceback (most recent call last): 
  File "C:/Users/Chad LaFarge/PycharmProjects/APIAccess/YouTubeAPI.py", line 33, in <module> 
    print(respData) 
  File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
UnicodeEncodeError: 'charmap' codec can't encode character '\u25bb' in position 11737: character maps to <undefined> 

更新

MJY 调用了它! 从 PyCharm 菜单栏开始: 文件 -> 设置... -> 编辑器 -> 文件编码,然后设置:“IDE 编码”、“项目编码”和“属性文件的默认编码”全部为 UTF-8,她现在工作得很好。

非常感谢!

请您参考如下方法:

检查sys.stdout.encoding。
如果这不是 UTF-8,则问题不在 YouTube API 中。
请检查环境变量 PYTHONIOENCODING、终端和语言环境设置。