Python Pytube – Retrieve search results from YouTube

In this post we will be creating a Python script that will retrieve search results from YouTube, to download YouTube captions we will be using pytube which is a lightweight, Pythonic, dependency-free, library for downloading YouTube Videos. The library is very easy to use and quite intuitive.

The project will take queries via user input and pass this as a search to the pytube API. The result will consist of the name of the video as well as the URL, both of which are then printed as output.

The source code for this project can be found below.

from pytube import Search

def SearchContent(Query):
    s = Search(Query)
    for v in s.results:
        print(str(f"{v.title}\n{v.watch_url}\n\n"))

while True:    
    Query = input("Enter Your search: ")
    print(SearchContent(Query))

An example output when querying ‘United Kingdom’ can be found below.

United Kingdom Song - A fun kid's song about the UK and its capitals for EYFS, KS1 & KS2
https://youtube.com/watch?v=RvDIZoQLgIE


The United Kingdom for Primary Schools | KS1 & KS2



The United Kingdom 4K - Scenic Relaxation Film With Calming Music



The Difference between the UK, Great Britain & England Explained



West England



10 Best Places to Visit in England - Travel Video



The 5 Hardest British Accents to Understand!



Top 10 Places To Visit In The UK
https://youtube.com/watch?v=0kXCPo7c63I

Leave a Reply