In this post we will be creating a Python script that will retrieve YouTube search results. To achieve this we will be using the youtubesearchpython library. The library allows us to search and get information about videos on YouTube using Python. It provides an easy-to-use interface for accessing the YouTube Data API v3 and parsing the JSON responses returned by the API.
See the sample of Python code below where we retrieve YouTube search results. The results in this example are limited to 5 per search although this can be changed.
We start by prompting the user to enter a search term, which is then stored in the query
variable. The code then creates a new VideosSearch
object, which searches for the top 5 YouTube videos that match the user’s search term. Next we start a loop that iterates over each video result returned by the search. We then print the Title, URL, duration and URL thumbnail for each result.
from youtubesearchpython import VideosSearch
while True:
query=input("Please enter search term: ")
videos_search = VideosSearch(query, limit=5)
for result in videos_search.result()['result']:
print(f"Title: {result['title']}")
print(f"URL: {result['link']}")
print(f"Duration: {result['duration']}")
print(f"Thumbnail: {result['thumbnails'][0]['url']}")
print()
Take a look at some of our other content around the Python programming language by clicking here.