我正在使用YouTube API检索视频数据。我有一个视频ID列表。对于一些视频,返回的结果是正常的,而对于其中一些视频,API返回零结果。通过我的浏览器,所有结果都是有效的。这是我的代码:
def getVideoDuration(self,videoId):
try:
content = urllib2.urlopen("https://www.googleapis.com/youtube/v3/videos?part=statistics%2C+contentDetails&id=" + videoId +"&key=" + self.DEVELOPER_KEY).read()
jsonContent= json.loads(content)
duration = jsonContent['items'][0].values()[0]['duration']
if len(duration) == 7:
minutes = jsonContent['items'][0].values()[0]['duration'][2]
seconds = jsonContent['items'][0].values()[0]['duration'][4:6]
if len(duration) == 5:
minutes = 0
seconds = jsonContent['items'][0].values()[0]['duration'][2:4]
print minutes,seconds
totalTime = str(minutes) + "." + str(seconds)
return float(totalTime)
except:
return 0.0
对于ID:'fu5K2cOeD4M'
,我的代码返回零结果,但通过我的浏览器,结果是正常的(附加JSON响应):
{
"kind": "youtube#videoListResponse",
"etag": ""0KG1mRN7bm3nResDPKHQZpg5-do/wTtZkXqw81l7Hq6-GrLwJ3wRQ5w"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": ""0KG1mRN7bm3nResDPKHQZpg5-do/jrxp-dHXG3s3ujaIjyq15GWV7V8"",
"id": "fu5K2cOeD4M",
"contentDetails": {
"duration": "PT8M15S",
"dimension": "2d",
"definition": "sd",
"caption": "false",
"licensedContent": false
},
"statistics": {
"viewCount": "18358",
"likeCount": "166",
"dislikeCount": "1",
"favoriteCount": "0",
"commentCount": "33"
}
}
]
}
我试图使用time.sleep()在请求之间进行延迟,但这对我没有帮助。
问题是我发送了请求,并添加了一个额外的字符