PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 2, 2022

[FIXED] How to paginate search with YouTube Data Api on Python?

 September 02, 2022     pagination, python, web-scraping, youtube-data-api     No comments   

Issue

I need to analyze all id's from search and in order 50 maxResults is not relevant for me, im trying to increase number of retrieved data by pagination. I want to understand how to do that.

Here is how my code look like:

api_key = "***************"

from googleapiclient.discovery import build
youtube = build('youtube','v3',developerKey = api_key)
print(type(youtube))

request = youtube.search().list(
    q='my unique search query',
    part='id',
    maxResults=50,
    order="viewCount",
    pageToken="CAoQAA",
    type='video')


print(type(request))
res = request.execute()
from pprint import PrettyPrinter
pp = PrettyPrinter()
pp.pprint(res)


Solution

According to documentation about pagination, you need to loop your requests to YouTube Data API v3 Search: list endpoint by providing as pageToken the retrieved nextPageToken if there is any. So your code becomes:

api_key = "***************"

from googleapiclient.discovery import build
from pprint import PrettyPrinter
youtube = build('youtube','v3',developerKey = api_key)
print(type(youtube))

pp = PrettyPrinter()
nextPageToken = ''

while True:
    request = youtube.search().list(
        q='my unique search query',
        part='id',
        maxResults=50,
        order="viewCount",
        pageToken=nextPageToken,
        type='video')
    
    print(type(request))
    res = request.execute()
    pp.pprint(res)
    
    if 'nextPageToken' in res:
        nextPageToken = res['nextPageToken']
    else:
        break


Answered By - Benjamin Loison
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing