Skip to content

Instantly share code, notes, and snippets.

@eevmanu
Created October 25, 2021 23:27
Show Gist options
  • Save eevmanu/3ad125e3c8420dd1784c4211313cfca9 to your computer and use it in GitHub Desktop.
Save eevmanu/3ad125e3c8420dd1784c4211313cfca9 to your computer and use it in GitHub Desktop.
Youtube video stats - get number of views, published date and duration of a video
#!/usr/bin/env python
import sys
import datetime
import argparse
import urllib.request
parser = argparse.ArgumentParser()
parser.add_argument('yt_video_url', type=str)
args = parser.parse_args()
yt_video_url = args.yt_video_url
url_prefix = "https://www.youtube.com/watch?v="
if yt_video_url.find(url_prefix) == -1:
yt_video_url = url_prefix + yt_video_url
with urllib.request.urlopen(yt_video_url) as u:
content = str(u.read(), 'utf-8')
# <meta itemprop="interactionCount" content="395882">
pattern = "itemprop=\"interactionCount\" content=\""
pos_start = content.find(pattern)
if pos_start == -1:
sys.exit()
pos_start = pos_start + len(pattern)
pos_end = content.find("\"", pos_start)
if pos_end == -1:
sys.exit()
yt_video_views = int(content[pos_start : pos_end])
# <meta itemprop="datePublished" content="2020-04-20">
pattern = "itemprop=\"datePublished\" content=\""
pos_start = content.find(pattern)
if pos_start == -1:
sys.exit()
pos_start = pos_start + len(pattern)
pos_end = content.find("\"", pos_start)
if pos_end == -1:
sys.exit()
yt_video_published_date = content[pos_start : pos_end]
# "lengthSeconds":"45585"
pattern = "\"lengthSeconds\":\""
pos_start = content.find(pattern)
if pos_start == -1:
sys.exit()
pos_start = pos_start + len(pattern)
pos_end = content.find("\"", pos_start)
if pos_end == -1:
sys.exit()
yt_video_duration = int(content[pos_start : pos_end])
yt_video_duration = str(datetime.timedelta(seconds=yt_video_duration))
print(f"{yt_video_views!r} | {yt_video_published_date!s} | {yt_video_duration!s}")
if __name__ == '__main__':
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment