Python 3.4 中的 YouTube API UnicodeEncodeError [英] YouTube API UnicodeEncodeError in Python 3.4
问题描述
我在探索 YouTube 数据 API 时发现编码不当的结果阻碍了我.我得到了很好的结果,直到我检索到一个在标题中包含未映射字符的集合.我的代码现在是(为你们这些好人清理了一点):
导入 urllib.request导入 urllib.parse导入json导入日期时间# 查找发布到 THIS MANY 小时前的视频IntHoursToSub = 2RightNow = datetime.datetime.utcnow()StartedAgo = datetime.timedelta(hours=-(IntHoursToSub))HourAgo = RightNow + StartedAgoHourAgo = str(HourAgo).replace(" ", "T")HourAgo = HourAgo[:HourAgo.find(".")] + "Z"# 从你安全的地方获取 API Key 并设置 API 链接YouTubeAPIKey = open('YouTubeAPIKey.txt', 'r').read()locuURL = "https://www.googleapis.com/youtube/v3/search"values = {"key": YouTubeAPIKey,"part": "片段","publishedAfter": HourAgo,"relevanceLanguage": "zh","regionCode": "我们","maxResults": "50",类型":直播"}postData = urllib.parse.urlencode(values)fullURL = locuURL + "?"+ postData# 设置响应持有者并处理异常响应数据 = ""尝试:req = urllib.request.Request(fullURL)respData = urllib.request.urlopen(req).read().decode()除了作为 e 的例外:打印(str(e))#print(respData)# 读取 JSON 响应并遍历视频名称/URLjsonData = json.loads(respData)对于 jsonData["items"] 中的对象:如果对象[id"][种类"] ==youtube#video":打印(对象[片段"][标题"],https://www.youtube.com/watch?v="+对象[id"][videoId"])
错误是:
回溯(最近一次调用最后一次): 中的文件C:/Users/Chad LaFarge/PycharmProjects/APIAccess/YouTubeAPI.py",第 33 行打印(响应数据)文件C:\Python34\lib\encodings\cp1252.py",第 19 行,在编码中返回 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
、终端和区域设置.
I was exploring the YouTube Data API and finding that improperly encoded results were holding me back. I got good results until I retrieve a set that includes unmapped characters in the titles. My code is NOW (cleaned up a little for you fine folks):
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"])
The error was:
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>
UPDATE
MJY Called it! Starting from PyCharm menu bar: File -> Settings... -> Editor -> File Encodings, then set: "IDE Encoding", "Project Encoding" and "Default encoding for properties files" ALL to UTF-8 and she now works like a charm.
Many thanks!
Check the sys.stdout.encoding
.
If this is not UTF-8
, the problem is not in YouTube API.
Please check such as environment variables PYTHONIOENCODING
, terminal and locale settings.
这篇关于Python 3.4 中的 YouTube API UnicodeEncodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!