How To Scrap YouTube Comments?
![]()
Web Scraping is the process of importing information from a website into local files saved on your computer. Later on you can use that information for analysis purpose.
Here, we will see how we can scrap YouTube comments and generate csv file from scraped data.
1. Prerequisite:
- You will require Google API Key (You can refer to this linkto generate API Key)
- Put key inside .env file
2. Import required packages:
3. Functiona to get video id using URL:
4. Function to scrap comments:
5. Function calls:
6. Check output:
- Inside data directory you will be able to see .csv file of scraped comments.
You will be able to download Source Code for Python backend and React front end from my GitHub account here.
You can check my another blog on how to use this data to explore NLP techniques here.
Сохраняем комментарии youtube в csv
Как-то на одном youtube канале, устроили розыгрыш среди комментаторов.
Условием было угадать цену закрытия акций хотя бы одной из трёх конкретных компаний.
Мне стало интересно собрать статистику за какие цены пользователи голосовали больше других и сработал ли «коллективный разум», когда пусть каждый отдельно взятый голос был далёк от истины, но среднее значение голосов внезапно попадало в точку.
Плюс задача сбора статистики усложнялась тем, что комментарии написаны в единое текстовое поле, а не в форму, где все значения на своих местах и нужного типа.
Заспойлерю: распарсить комментарии оказалось самой трудоёмкой задачей, потому что не было даже единой схемы ответа (ок была превалирующая, но далеко не единственная):
одни писали сначала название компании потом цену, другие — наоборот цену, потом компанию (кое-кто писал название, много вводных слов обосновывающих его мысли и потом цену)
Где-то было название, где-то тикер
Местами текст был на английском, местами на русском
Дробные части отделяли и точками и запятыми
Встречались и опечатки в несколько букв (в одном слове)
Многие сокращали название до двух букв, сочетание которых очевидно встречалась и в обычных комментариях, не связанных с конкурсом
Были и жаргонные названия компаний (Бумер вместо BMW), и наоборот полные (Bayerische Motoren Werke)
Но призёрами в борьбе с парсингом стали люди, писавшие в словах Tesla и BMW — русскую букву «т» и русскую «в» в начале слова, а дописывавшие его английскими буквами
(последнее заметил по чистой случайности просматривая json содержимое, когда латиница идёт буквами, а весь юникод заменяется слешами с кодами)
Во-первых, не все хотят платить за то, что можно получить бесплатно.
Во-вторых, не у всех хорошо с английским, да и зачем курить длинные мануалы, если задача узкая и односложная.
В-третьих, никакой похожей инструкции на первой странице поиска не нашлось, думаю это нужно исправить.
Чтобы инструкция была более гибкой и её можно было использовать, даже если что-то изменится в одном из шагов, в каждом оставлю источники.
Получите ключ для работы с youtube API (источник)
Возьмитие ваш гугл-аккаунт и создайте проект по ссылке https://console.developers.google.com/
Создайте новый API ключ
Перейдите к странице включения сервисов для API
Найдите YouTube Data API v3
Получите библиотеку google-api-python-client (источник)
pip.exe install google-api-python-client
Возьмите редактор, например visual studio code
Создайте новый python файл и вставьте в него следующий код
Всё что вам нужно в нём поправить для старта это
DEVELOPER_KEY — получен в первом пункте
VIDEO_ID — берётся из ссылки на видео, например в ссылке https://youtu.be/9b4-G-czN5Y нас интересует 9b4-G-czN5Y
В полученной таблице все поля, которые доступны по YouTube API.
Созданный csv отлично открывается в LibreOffice Calc.
Используются двойные кавычки и разделитель запятая, кодировка UTF-8.
Если нужно отличить корневой комментарий от реплая можно добавить столбец с сравнением parentid с id — в случае их равенства комментарий корневой, иначе реплай.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Simple script for downloading Youtube comments without using the Youtube API
License
egbertbouman/youtube-comment-downloader
Name already in use
- Local
- Codespaces
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI.
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Simple script for downloading Youtube comments without using the Youtube API. The output is in line delimited JSON.
Preferably inside a python virtual environment install this package via:
Or directly from the GitHub repository:
Usage as command-line interface
or using the Youtube ID:
For Youtube IDs starting with — (dash) you will need to run the script with: -y=idwithdash or —youtubeid=idwithdash
Usage as library
You can also use this script as a library. For instance, if you want to print out the 10 most popular comments for a particular Youtube video you can do the following:
About
Simple script for downloading Youtube comments without using the Youtube API
How to Download all Comments from any YouTube Videos
This tutorial explains how to download all comments from any YouTube video. To do this here I will mention a simple script that uses YouTube API to download comments in on your PC. Basically the script gets all the comments from any given YouTube video and then save them in a JSON file. You can then open that file in Excel or convert to other formats such as CSV with ease. The script is simple and only takes YouTube ID and output file name from you and then does its job automatically.
Quite some time ago we cover order online YouTube comment downloader. But that does not seem to be working right now, so I am introducing this new script here. It works very efficiently as it replicates the original YouTube API calls to scrape the data from them the comments on your computer. And there is no login or something like that is required in order to make it work. All you need is Python and you can run it on Windows, Mac, and Linux PC. You can see the progress of downloading comments on the terminal window. And when it is done, you can explore the output file.
How to Download all Comments from any YouTube Videos?
Getting started with this script is very simple. You just need Python2 installed on your computer. If you don’t have Python already then you can download it from here. After that, you run the following command to set up some dependencies. After this, you are ready to use the script.

Simply clone it from its GitHub repository using the git command. Or, you can download the zip file manually. Find the “downloader.py” file and then make sure that the terminal or the command prompt pointing to the current directory. After that, you just run the following command and then it will start downloading comments. You just have to specify the YouTube video ID and name of the output file. This is as simple as that.

In the above screenshot, you can see how this simple command line script to download comments from any YouTube video. And it downloads all the comments in a JSON file. You can later use that file however you want. There are some online as well software to convert JSON file to CSV and other spreadsheet formats. You can make use of those software, if you want the data in another format.
Closing words:
The problem with the traditional is scraping is that it takes a lot of time. But the script that I have mentioned here does smart work by replicating the actual AJAX requests that YouTube uses behind the scene to render comments. With this, you can get thousands of comments on your PC from any YouTube video in just few seconds. I really liked the functionality of the Script and you can use it very easily as well.