Update:
As of this current posting, I do have ids=ids in the fuction in question, however when changing that to be id=ids, I get the same errors. Perhaps by viewing the full code, it may make it more obvious as to why this is happening.
Here's full code:
#Write a script that writes a csv file with a list of the top most viewed YouTube videos.
#The script should take a YouTube API key as an argument and use it to query the YouTube Data API for the topmost viewed videos.
#The script should then write the video title, video view count, and video ID to a csv file.
#The script should also print the total number of views to a file.
import csv
import os
import argparse
from googleapiclient.discovery import build
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "---hidden---"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
# Call the search.list method to retrieve results matching the specified
# query term.
search_response = youtube.search().list(
q=options.q,
part="id,snippet",
maxResults=options.max_results
).execute()
ids = [item["id"]["videoId"] for item in search_response["items"]]
search_response = youtube.videos().list(
part="statistics",
ids=ids
).execute()
videos_with_view_counts = [[item["id"], item["statistics"]["viewCount"]] for item in search_response["items"]]
return videos_with_view_counts
# Add each result to the appropriate list, and then display the lists of
# matching videos, channels, and playlists.
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append(search_result)
return videos
def main():
parser = argparse.ArgumentParser(description='Search on YouTube')
parser.add_argument("--q", help="Search term", default="Google")
parser.add_argument("--max-results", help="Max results", default=25)
args = parser.parse_args()
try:
os.remove('top_videos.csv')
except OSError:
pass
with open('top_videos.csv', 'w') as csvfile:
fieldnames = ['title', 'viewCount', 'videoId']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for video in youtube_search(args): # video is a dictionary
print("Title: %s" % video['snippet']['title']) # Print video title
print("View Count: %s" % video['statistics']['viewCount']) # video['statistics']['viewCount']
print("Video ID: %s" % video['id']['videoId']) # videoId
print("\n") # blank line
writer.writerow({'title': video['snippet']['title'], 'viewCount': video['statistics']['viewCount'], 'videoId': video['id']['videoId']})
if __name__ == "__main__":
main()
The errors I got from ((your code + Copilot's code)) are below:
Traceback (most recent call last):
File "c:\Users\brian\Documents\GitHub\scripts\top-youtube.py", line 75, in <module>
main()
File "c:\Users\brian\Documents\GitHub\scripts\top-youtube.py", line 66, in main
for video in youtube_search(args): # video is a dictionary
File "c:\Users\brian\Documents\GitHub\scripts\top-youtube.py", line 31, in youtube_search
ids = [item["id"]["videoId"] for item in search_response["items"]]
File "c:\Users\brian\Documents\GitHub\scripts\top-youtube.py", line 31, in <listcomp>
ids = [item["id"]["videoId"] for item in search_response["items"]]
KeyError: 'videoId'
I suspect that other parts of the code are causing the problem, not the function itself. I am not opposed to cutting anything out of the script necessary to make it search all of YouTube and return a list of the top say 1000 videos in ascending order weighted by views, likes, subs in that order. If that is indeed YouTube's algorithm for how they calculate rewards for content creators. My idea is to use this information to start creating channels that can earn passive income, no matter how small, that can then through the use of Python and APIs be funneled into my exchange accounts to then be traded by Python trading bots.
Anything from a YouTube channel is better than nothing. I also know about the fact that you can funnel traffic to your YouTube videos/channels from websites and social media accounts. Not looking to get rich off of YouTube, looking to create a steady trickle of currency that can then be traded. YouTube is not expected to do the bulk of the heavy lifting here, just to be a source among possibly many. So, my idea is to use this script initially to get ideas for channels and videos, content, and success rates. If you know a better way to do this, please let me know.
The full script is here.
