我正在探索YouTube数据API并发现不正确编码的结果阻碍了我。我得到了很好的结果,直到我检索到一个包含标题中未映射字符的集合。我的代码现在是(为你们精心清理了一点):
button.et_bloom_submit_subscription {
float: right;
position: fixed;
top: 7px;
right: 310px;
}
.et_bloom .et_bloom_form_content .et_bloom_popup_input {
width: 25%;
}
button.et_bloom_submit_subscription {
width: 21% !important;
}
.et_bloom .et_bloom_inline_form {
left padding: 60px;
}
.et_bloom .et_bloom_inline_form {
margin: 0;
}
.et_bloom .et_bloom_header_outer {
display: none;
}
@media only screen and (max-width:1100px) {
.page-id-453 .et_bloom_form_content {
width: 100% !important;
margin: 0 auto !important;
}
.page-id-453 .et_bloom_form_content .et_bloom_popup_input {
width: 25% !important;
margin-right:2%;
}
.page-id-453 .et_bloom_form_container button {
width: 45% !important;
padding:13px;
top:auto !important;
left: auto !important;
margin: auto !important;
float: right !important;
}
}
错误是:
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"])
更新
MJY叫它!从PyCharm菜单栏开始: 档案 - >设置... - >编辑 - >文件编码,然后设置:" IDE编码","项目编码"和"属性文件的默认编码" ALL到UTF-8,她现在就像一个魅力。
非常感谢!
答案 0 :(得分:2)
检查sys.stdout.encoding
。
如果这不是UTF-8
,则问题不在YouTube API中
请检查环境变量PYTHONIOENCODING
,终端和区域设置等。