Web Scraping Youtube

W

How To Scrape & Export Video Information from YouTube

How To Scrape & Export Video Information from YouTube

You’re ready to audit and optimize your (or your clients’) YouTube channel or you want to see what a competitor is doing with their YouTube videos. But you run into the problem that YouTube makes it kind of tough to scrape and export video information.
You can’t really crawl YouTube like you can a website – it’s too large and there’s no way to control your crawl. I ran into this problem a few weeks ago while trying to map out videos and optimize titles & tags in bulk.
Here’s how to scrape & export video information from YouTube without buying sketchy blackhat scraper software.
1. Get Your Setup Ready
You’re going to need:
Scraper for Chrome (free) to scrape the video URLs.
Google Sheets (free) to organize the data.
Screaming Frog (free up to 500 URLs) to crawl your videos.
2. Load up all your YouTube videos
You’re going to just keep loading more videos until you can’t load anymore.
*Some readers are reporting that YouTube will occasionally block scraping on their main app. To get around that, before pressing Scrape Similar, change the URL to m. Then you’ll be redirected to a page which ends in =desktop. Same content, but no scraper blocking Javascript (you can also hunt down & block the blocking script as well). h/t Exequiel Plaza.
3. Scrape the YouTube videos
Right-click on any video link, then click Scrape Similar.
Double-check that it has scraped all the videos, then Export to Google Docs.
4. Clean up your URLs and save to text file
In your Google Doc, add onto all the URLs
Then (if necessary) strip any unneeded parameters from the videos (such as &list)
5. Get your list into Screaming Frog
Copy and paste your list of URLs into a TextEdit (Mac) or Notepad (Windows) and Save as a file
Now open Screaming Frog and set it to List Mode, then crawl.
6. Get it back into a spreadsheet
Export your Screaming Frog crawl to a or and move the data to either Microsoft Excel or back to Google Sheets.
7. Use the data!
You will be primarily be looking at the Title and Meta Keywords columns. Many SEOs know that YouTube uses your video tags as a relevance & quality signal.
However, many SEOs do not know that YouTube stores the video Tag information in the otherwise useless Meta Keywords field.
Aside – just so there’s no confusion, Google does not use the meta keywords tag to gauge relevance of websites. YouTube does use Tags to judge relevance of videos hosted on YouTube. The tags are stored in the meta keywords field.
You can also use the data to judge meta descriptions & word count at scale to spot optimization opportunities.
Bonus!
Screaming Frog also has a Custom Extraction function. If you can find the Xpath of any HTML element on a YouTube page, then you can scrape it.
For example, if you want a point in time of YouTube views on your list of videos. Just grab the Xpath of the element via right-click, Inspect Element, Copy Xpath.
And then drop that Xpath in the Custom Extraction section of Screaming Frog.
Note – you may have to fiddle with the User Agent to keep from being blocked. Either way – it’s a useful tool for quick analysis.
2nd Note – you may also have to change the Rendering setting under Spider to “Javascript” instead of “Text Only” since YouTube loads a lot of page assets dynamically (notably, the view count).
Next Steps & Additional Thoughts
Go grab Scraper for Chrome and Screaming Frog and start pulling your YouTube information into a spreadsheet! Once you have your data in order, be sure to take advantage of YouTube’s bulk editor to quickly edit tags & meta information.
Don’t forget that the Meta Keywords field is on every YouTube video, so definitely spy on and leverage your competitor’s YouTube video information.
Read more about analyzing your own YouTube Analytics here.
I’m Nate Shivar – a marketing educator, consultant, and formerly Senior SEO Specialist at a marketing agency in Atlanta, GA. I try to help people who run their own them a little better. I like to geek out on Marketing, SEO, Analytics, and Better Websites. Read more About me. Sponsored Links
Is Web Scraping Illegal? Depends on What the Meaning of the Word Is

Is Web Scraping Illegal? Depends on What the Meaning of the Word Is

Depending on who you ask, web scraping can be loved or hated.
Web scraping has existed for a long time and, in its good form, it’s a key underpinning of the internet. “Good bots” enable, for example, search engines to index web content, price comparison services to save consumers money, and market researchers to gauge sentiment on social media.
“Bad bots, ” however, fetch content from a website with the intent of using it for purposes outside the site owner’s control. Bad bots make up 20 percent of all web traffic and are used to conduct a variety of harmful activities, such as denial of service attacks, competitive data mining, online fraud, account hijacking, data theft, stealing of intellectual property, unauthorized vulnerability scans, spam and digital ad fraud.
So, is it Illegal to Scrape a Website?
So is it legal or illegal? Web scraping and crawling aren’t illegal by themselves. After all, you could scrape or crawl your own website, without a hitch.
Startups love it because it’s a cheap and powerful way to gather data without the need for partnerships. Big companies use web scrapers for their own gain but also don’t want others to use bots against them.
The general opinion on the matter does not seem to matter anymore because in the past 12 months it has become very clear that the federal court system is cracking down more than ever.
Let’s take a look back. Web scraping started in a legal grey area where the use of bots to scrape a website was simply a nuisance. Not much could be done about the practice until in 2000 eBay filed a preliminary injunction against Bidder’s Edge. In the injunction eBay claimed that the use of bots on the site, against the will of the company violated Trespass to Chattels law.
The court granted the injunction because users had to opt in and agree to the terms of service on the site and that a large number of bots could be disruptive to eBay’s computer systems. The lawsuit was settled out of court so it all never came to a head but the legal precedent was set.
In 2001 however, a travel agency sued a competitor who had “scraped” its prices from its Web site to help the rival set its own prices. The judge ruled that the fact that this scraping was not welcomed by the site’s owner was not sufficient to make it “unauthorized access” for the purpose of federal hacking laws.
Two years later the legal standing for eBay v Bidder’s Edge was implicitly overruled in the “Intel v. Hamidi”, a case interpreting California’s common law trespass to chattels. It was the wild west once again. Over the next several years the courts ruled time and time again that simply putting “do not scrape us” in your website terms of service was not enough to warrant a legally binding agreement. For you to enforce that term, a user must explicitly agree or consent to the terms. This left the field wide open for scrapers to do as they wish.
Fast forward a few years and you start seeing a shift in opinion. In 2009 Facebook won one of the first copyright suits against a web scraper. This laid the groundwork for numerous lawsuits that tie any web scraping with a direct copyright violation and very clear monetary damages. The most recent case being AP v Meltwater where the courts stripped what is referred to as fair use on the internet.
Previously, for academic, personal, or information aggregation people could rely on fair use and use web scrapers. The court now gutted the fair use clause that companies had used to defend web scraping. The court determined that even small percentages, sometimes as little as 4. 5% of the content, are significant enough to not fall under fair use. The only caveat the court made was based on the simple fact that this data was available for purchase. Had it not been, it is unclear how they would have ruled. Then a few months back the gauntlet was dropped.
Andrew Auernheimer was convicted of hacking based on the act of web scraping. Although the data was unprotected and publically available via AT&T’s website, the fact that he wrote web scrapers to harvest that data in mass amounted to “brute force attack”. He did not have to consent to terms of service to deploy his bots and conduct the web scraping. The data was not available for purchase. It wasn’t behind a login. He did not even financially gain from the aggregation of the data. Most importantly, it was buggy programing by AT&T that exposed this information in the first place. Yet Andrew was at fault. This isn’t just a civil suit anymore. This charge is a felony violation that is on par with hacking or denial of service attacks and carries up to a 15-year sentence for each charge.
In 2016, Congress passed its first legislation specifically to target bad bots — the Better Online Ticket Sales (BOTS) Act, which bans the use of software that circumvents security measures on ticket seller websites. Automated ticket scalping bots use several techniques to do their dirty work including web scraping that incorporates advanced business logic to identify scalping opportunities, input purchase details into shopping carts, and even resell inventory on secondary markets.
To counteract this type of activity, the BOTS Act:
Prohibits the circumvention of a security measure used to enforce ticket purchasing limits for an event with an attendance capacity of greater than 200 persons.
Prohibits the sale of an event ticket obtained through such a circumvention violation if the seller participated in, had the ability to control, or should have known about it.
Treats violations as unfair or deceptive acts under the Federal Trade Commission Act. The bill provides authority to the FTC and states to enforce against such violations.
In other words, if you’re a venue, organization or ticketing software platform, it is still on you to defend against this fraudulent activity during your major onsales.
The UK seems to have followed the US with its Digital Economy Act 2017 which achieved Royal Assent in April. The Act seeks to protect consumers in a number of ways in an increasingly digital society, including by “cracking down on ticket touts by making it a criminal offence for those that misuse bot technology to sweep up tickets and sell them at inflated prices in the secondary market. ”
In the summer of 2017, LinkedIn sued hiQ Labs, a San Francisco-based startup. hiQ was scraping publicly available LinkedIn profiles to offer clients, according to its website, “a crystal ball that helps you determine skills gaps or turnover risks months ahead of time. ”
You might find it unsettling to think that your public LinkedIn profile could be used against you by your employer.
Yet a judge on Aug. 14, 2017 decided this is okay. Judge Edward Chen of the U. S. District Court in San Francisco agreed with hiQ’s claim in a lawsuit that Microsoft-owned LinkedIn violated antitrust laws when it blocked the startup from accessing such data. He ordered LinkedIn to remove the barriers within 24 hours. LinkedIn has filed to appeal.
The ruling contradicts previous decisions clamping down on web scraping. And it opens a Pandora’s box of questions about social media user privacy and the right of businesses to protect themselves from data hijacking.
There’s also the matter of fairness. LinkedIn spent years creating something of real value. Why should it have to hand it over to the likes of hiQ — paying for the servers and bandwidth to host all that bot traffic on top of their own human users, just so hiQ can ride LinkedIn’s coattails?
I am in the business of blocking bots. Chen’s ruling has sent a chill through those of us in the cybersecurity industry devoted to fighting web-scraping bots.
I think there is a legitimate need for some companies to be able to prevent unwanted web scrapers from accessing their site.
In October of 2017, and as reported by Bloomberg, Ticketmaster sued Prestige Entertainment, claiming it used computer programs to illegally buy as many as 40 percent of the available seats for performances of “Hamilton” in New York and the majority of the tickets Ticketmaster had available for the Mayweather v. Pacquiao fight in Las Vegas two years ago.
Prestige continued to use the illegal bots even after it paid a $3. 35 million to settle New York Attorney General Eric Schneiderman’s probe into the ticket resale industry.
Under that deal, Prestige promised to abstain from using bots, Ticketmaster said in the complaint. Ticketmaster asked for unspecified compensatory and punitive damages and a court order to stop Prestige from using bots.
Are the existing laws too antiquated to deal with the problem? Should new legislation be introduced to provide more clarity? Most sites don’t have any web scraping protections in place. Do the companies have some burden to prevent web scraping?
As the courts try to further decide the legality of scraping, companies are still having their data stolen and the business logic of their websites abused. Instead of looking to the law to eventually solve this technology problem, it’s time to start solving it with anti-bot and anti-scraping technology today.
Get the latest from imperva
The latest news from our experts in the fast-changing world of application, data, and edge security.
Subscribe to our blog
How to Extract YouTube Data in Python

How to Extract YouTube Data in Python

·
12 min read
· Updated
sep 2021
· Web Scraping
Web scraping is extracting data from websites. It is a form of copying, in which specific data is gathered and copied from the web into a central local database or spreadsheet for later analysis or retrieval.
Since YouTube is the biggest video sharing website in the internet, extracting data from it can be very helpful, you can find the most popular channels, keeping track on the popularity of channels, recording likes, dislikes and views on videos and much more. In this tutorial, you will learn how to extract data from YouTube videos using requests_html and BeautifulSoup in Python.
Note that it isn’t reliable to use this method to extract YouTube data, as YouTube keeps changing their code, the code can not work in any time. Therefore, for more reliable use, I suggest you use YouTube API for extracting data instead.
Related: How to Extract YouTube Comments in Python.
Installing required dependencies:
pip3 install requests_html bs4
Before we dive into the quick script, we gonna need to experiment on how to extract such data from websites using BeautifulSoup, open up a Python interactive shell and write these lines of code:
from requests_html import HTMLSession
from bs4 import BeautifulSoup as bs # importing BeautifulSoup
# sample youtube video url
video_url = ”
# init an HTML Session
session = HTMLSession()
# get the html content
response = (video_url)
# execute Java-script
(sleep=1)
# create bs object to parse HTML
soup = bs(, “”)
This makes a request to that YouTube video URL, renders the Javascript and finally creates the BeatifulSoup object wrapping the resulting HTML.
Great, now let’s try to find all meta tags in the page:
In [10]: nd_all(“meta”)
Out[10]:
[,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
]
Easy as that, a lot of useful data here. For example, we can get the video title by:
In [11]: (“meta”, itemprop=”name”)[“content”]
Out[11]: ‘Me at the zoo’
Or the number of views:
In [12]: (“meta”, itemprop=”interactionCount”)[‘content’]
Out[12]: ‘172826227’
This way, you will be able to extract everything you want from that web page. Now let’s make our script that extracts some useful information we can get from a YouTube video page, open up a new Python file and follow along:
Importing necessary modules:
from bs4 import BeautifulSoup as bs
Before we make our function that extract all video data, let’s initialize our HTTP session:
# init session
Let’s make a function, given an URL of a YouTube video, it will return all the data in a dictionary:
def get_video_info(url):
# download HTML code
response = (url)
# execute Javascript
# create beautiful soup object to parse HTML
# open(“”, “w”)()
# initialize the result
result = {}
Notice after we downloaded the HTML content of the web page, we ran render() method to execute Javascript, so that the data we’re looking for, is rendered in the HTML.
Note that if you get timeout error, then you can simply add timeout parameter and set it to 60 seconds (default is 8 seconds) or something, like so:
(sleep=1, timeout=60)
Retrieving the video title:
# video title
result[“title”] = (“meta”, itemprop=”name”)[‘content’]
Number of views converted to an integer:
# video views (converted to integer)
result[“views”] = result[“views”] = (“meta”, itemprop=”interactionCount”)[‘content’]
Get the video description:
# video description
result[“description”] = (“meta”, itemprop=”description”)[‘content’]
The date when the video was published:
# date published
result[“date_published”] = (“meta”, itemprop=”datePublished”)[‘content’]
The duration of the video:
# get the duration of the video
result[“duration”] = (“span”, {“class”: “ytp-time-duration”})
We could get the duration from meta tag as previous fields, but it’ll be in another format, such as PT0M19S which translates to 19 seconds or 00:19 in the format that is in the ytp-time-duration span tag.
We can also extract the video tags:
# get the video tags
result[“tags”] = ‘, ‘([ (“content”) for meta in nd_all(“meta”, {“property”: “og:video:tag”})])
The number of likes and dislikes as integers:
# number of likes
text_yt_formatted_strings = nd_all(“yt-formatted-string”, {“id”: “text”, “class”: “ytd-toggle-button-renderer”})
result[“likes”] = ”([ c for c in text_yt_formatted_strings[0](“aria-label”) if digit()])
result[“likes”] = 0 if result[‘likes’] == ” else int(result[‘likes’])
# number of dislikes
result[“dislikes”] = ”([ c for c in text_yt_formatted_strings[1](“aria-label”) if digit()])
result[‘dislikes’] = 0 if result[‘dislikes’] == ” else int(result[‘dislikes’])
Since in a YouTube video, you can see the channel details, such as the name, and number of subscribers, let’s grab that as well:
# channel details
channel_tag = (“yt-formatted-string”, {“class”: “ytd-channel-name”})(“a”)
# channel name
channel_name =
# channel URL
channel_url = f”channel_tag[‘href’]}”
# number of subscribers as str
channel_subscribers = (“yt-formatted-string”, {“id”: “owner-sub-count”})()
result[‘channel’] = {‘name’: channel_name, ‘url’: channel_url, ‘subscribers’: channel_subscribers}
return result
Since () function returns a Tag object, you can still find HTML tags within other tags. As a result, It is a common practice to call find() more than once.
Now this function returns a lot of video information in a dictionary, let’s finish up our script:
if __name__ == “__main__”:
import argparse
parser = gumentParser(description=”YouTube Video Data Extractor”)
d_argument(“url”, help=”URL of the YouTube video”)
args = rse_args()
url =
# get the data
data = get_video_info(url)
# print in nice format
print(f”Title: {data[‘title’]}”)
print(f”Views: {data[‘views’]}”)
print(f”Published at: {data[‘date_published’]}”)
print(f”Video Duration: {data[‘duration’]}”)
print(f”Video tags: {data[‘tags’]}”)
print(f”Likes: {data[‘likes’]}”)
print(f”Dislikes: {data[‘dislikes’]}”)
print(f”\nDescription: {data[‘description’]}\n”)
print(f”\nChannel Name: {data[‘channel’][‘name’]}”)
print(f”Channel URL: {data[‘channel’][‘url’]}”)
print(f”Channel Subscribers: {data[‘channel’][‘subscribers’]}”)
Nothing special here, since we need a way to retrieve the video URL from the command line, the above does just that, and then print it in a format, here is my output when running the script:
C:\youtube-extractor>python Title: Me at the zoo
Views: 172639597
Published at: 2005-04-23
Video Duration: 0:18
Video tags: me at the zoo, jawed karim, first youtube video
Likes: 8188077
Dislikes: 191986
Description: The first video on YouTube. While you wait for Part 2, listen to this great song:
Channel Name: jawed
Channel URL: Channel Subscribers: 1. 98M subscribers
Conclusion
This is it! You know how to extract data from HTML tags, then go on and add other fields such as video quality and others.
Now If you want to extract YouTube comments, there are a lot of things to do besides this, there is a separate tutorial for this.
You can not only extract YouTube video details, but you can also apply this skill to any website you want. If you want to extract Wikipedia pages, there is a tutorial for that! Or maybe you want to scrape weather data from Google? There is a tutorial for that as well.
Check the full code of this tutorial here.
Note: YouTube constantly changes the HTML structure of video pages. If the code of this tutorial doesn’t work for you, please check out using YouTube API tutorial instead.
Want to Learn More about Web Scraping?
Finally, if you want to dig more into web scraping with different Python libraries, not just BeautifulSoup, the below courses will definitely be valuable for you:
Modern Web Scraping with Python using Scrapy Splash Selenium.
Web Scraping and API Fundamentals in Python 2021.
Learn also: How to Convert HTML Tables into CSV Files in Python.
Happy Scraping ♥
View Full Code
Read Also
Comment panel

Frequently Asked Questions about web scraping youtube

Is scraping YouTube legal?

Web scraping is now legal.

How do you scrape a YouTube video?

Scrape the YouTube videos Right-click on any video link, then click Scrape Similar. Double-check that it has scraped all the videos, then Export to Google Docs.May 7, 2021

Is Web scraping legal?

So is it legal or illegal? Web scraping and crawling aren’t illegal by themselves. After all, you could scrape or crawl your own website, without a hitch. … Big companies use web scrapers for their own gain but also don’t want others to use bots against them.

About the author

proxyreview

If you 're a SEO / IM geek like us then you'll love our updates and our website. Follow us for the latest news in the world of web automation tools & proxy servers!

By proxyreview

Recent Posts

Useful Tools