Python Script to search for YouTube Data trends

R. Eric Kiser
3 min readJan 15, 2023

R. Eric Kiser

As a subject matter expert, I wanted to gain insight into the topics that my readers and students are interested in. Given the increasing popularity of video platforms such as YouTube, I decided to use a Python script to pull data from Google Trends on a specific topic of interest, “hacking.” This script allows me to understand the current trends and popular search queries in the field, and tailor my content to align with the needs and interests of my audience. Below is the simple script that I created. I tend to do more with the project but that is for another day.

import requests
from pytrends.request import TrendReq

# create a new instance of the pytrends class
pytrend = TrendReq()

# prompt for keyword
keyword = input("Enter a keyword to search for data trends: ")

# set the parameters for the trend search
kw_list = [keyword]
timeframe = "today 1-m"

# get the trends
pytrend.build_payload(kw_list, cat=0, timeframe=timeframe, geo='', gprop='youtube')
trends = pytrend.interest_over_time()

# get the most searched queries
related_queries = pytrend.related_queries()

# print the trends
print(trends)

# print the most searched queries
print(related_queries)

The script is written in python and uses the pytrends library to interact with Google Trends and retrieve data. Making the task a very easy one! Of couse when you are dealing with grabbing data from the web you need to import the requests library. We don’t want to slow our script down so we will add the TrendReq class from the pytrends library to speed up the process. Then, an instance of the TrendReq class is created, and it's stored in the variable pytrend.

Next, the script prompts the user to enter a keyword to search for data trends. The keyword entered by the user is stored in the variable keyword.

Once a keyword is typed and enter is pressed, the parameters are set for the trend search. It creates a list of keywords, in this case, it’s a single keyword, and stores it in the variable kw_list. It also sets the time frame for the search, in this case, it's for the last month, stored in the variable timeframe.

The script then uses the build_payload method of the pytrend object, which takes the keyword list and the other parameters as inputs, and it grabs the trends related to the keywords searched in youtube. This is done by passing the gprop='youtube' parameter to the build_payload method. The script then stores the returned data in the variable trends and prints the trends in the console.

You can run this script in PowerShell or any other CLI. However, be sure to have the dependencies.

  1. pip
  2. requests
  3. pytrends

The End Result in PowerShell

--

--

R. Eric Kiser

R. Eric Kiser is highly skilled certified information security manager with 10+ years of experience in the field.