亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過 Youtube JSON 響應高效分頁?

如何通過 Youtube JSON 響應高效分頁?

慕神8447489 2022-05-19 13:59:17
我正在從 Youtube 頻道收集有關視頻的信息,該頻道的視頻數量 > 50。所以這意味著我需要發出幾個請求,因為每個 JSON 響應的最大結果是 50 個視頻。我找到了一些解決方案,現在代碼看起來像這樣videoMetadata = [] #declaring our list, where the results will be stored# First requesturl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='+CHANNEL_ID+'&maxResults=50&type=video&key='+API_KEYresponse = urllib.request.urlopen(url) #makes the call to YouTubevideos = json.load(response) #decodes the response so we can work with itnextPageToken = videos.get("nextPageToken") #gets the token of next page# Retrieve all the rest of the pageswhile nextPageToken:    url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='+CHANNEL_ID+'&maxResults=50&type=video&key='+API_KEY+"&pageToken="+nextPageToken    response = urllib.request.urlopen(url)    videos_next_page = json.load(response)    nextPageToken = videos_next_page.get("nextPageToken")# loops through results and appends it to videoMetadata list # loop for the first pagefor video in videos['items']:    if video['id']['kind'] == 'youtube#video':        videoMetadata.append(video['id']['videoId'])# loop for the next page       for video in videos_next_page['items']:    if video['id']['kind'] == 'youtube#video':它工作正常,但也許有更好的解決方案,我如何將多個 JSON 響應的結果存儲在列表中?將不勝感激任何建議。
查看完整描述

1 回答

?
慕雪6442864

TA貢獻1812條經驗 獲得超5個贊

它工作正常,


實際上,它沒有,除非你只有一個“下一頁” - 這個:


while nextPageToken:

    url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='+CHANNEL_ID+'&maxResults=50&type=video&key='+API_KEY+"&pageToken="+nextPageToken

    response = urllib.request.urlopen(url)

    videos_next_page = json.load(response)

    nextPageToken = videos_next_page.get("nextPageToken")

每次迭代都會覆蓋videos_next_page ,所以你只會得到最后一頁。


如何將來自多個 JSON 響應的結果存儲在列表中


一旦反序列化,“來自 JSON 響應的結果”就是普通的 Python 對象(通常是dicts)。并且您將它們附加到列表中,就像您對其他任何事情一樣。


這是一個可能的重寫,可以正確處理這個問題(并且也可以更好地利用內存) - 警告:未經測試的代碼,所以我不能保證沒有錯字或其他什么,但至少你明白了。


def load_page(page_token=None):

    url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={}&maxResults=50&type=video&key={}".format(CHANNEL_ID, API_KEY)

    if page_token:

        url += ("&pageToken={}".format(page_token))

    response = urllib.request.urlopen(url) #makes the call to YouTube

    return json.load(response)


def collect_videos_meta(page):

    return [video['id']['videoId'] for video in page['items'] if video['id']['kind'] == 'youtube#video']


def main():

    videoMetadata = []

    nextPageToken = None # default initial value for the first page


    # using `while True` and `break` avoids having to repeat the same

    # code twice (once before the loop and once within the loop).

    # This is a very common pattern in Python, you just have to make

    # sure you will break out of the loop at some point...


    while True:

        page = load_page(nextPageToken)

        videoMetadata.extend(collect_videos_meta(page))

        nextPageToken = page.get("nextPageToken")

        if not nextPageToken:

            break


    # now do what you want with those data...

    print(videoMetadata)



if __name__ = "__main__":

    main()


查看完整回答
反對 回復 2022-05-19
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號