0% found this document useful (0 votes)
41 views

YoutubeCommentBot Using Python

This document provides instructions for building a YouTube comment bot with Python and the Selenium library. It describes installing Selenium, opening the YouTube site in a browser, logging in with a username and password, entering a search term, clicking on a video, entering a comment, repeating the process on multiple videos, and putting all the steps together into a Python script with sample code. The goal is to automate interacting with YouTube videos by leaving comments, which can help grow one's audience by driving traffic to their channel from other channels.

Uploaded by

ANIK CHAKRABORTY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

YoutubeCommentBot Using Python

This document provides instructions for building a YouTube comment bot with Python and the Selenium library. It describes installing Selenium, opening the YouTube site in a browser, logging in with a username and password, entering a search term, clicking on a video, entering a comment, repeating the process on multiple videos, and putting all the steps together into a Python script with sample code. The goal is to automate interacting with YouTube videos by leaving comments, which can help grow one's audience by driving traffic to their channel from other channels.

Uploaded by

ANIK CHAKRABORTY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

Well obviously we are reading this but we also need to read the Selenium librairy Book

How To Build a Youtube Comment Bot with


Python
Posted by Marta on April 20, 2021 Viewed 28295 times

This tutorial will show you how to build a youtube comment bot step by step using Python and the
Selenium library. Building your youtube comment bot can help you grow your youtube audience as
interacting with other channels will drive traffic to your own channel.

Besides, building a youtube bot is an enjoyable thing to program. You will learn how to program the bot to
navigate the youtube site: open videos, click buttons and enter comments. Furthermore, you could
apply all selenium tricks in this tutorial to build bots for other websites.

Let’s dive in!

Table of Contents 

1. Overview
2. Step #1: Install Selenium
3. Step #2: Open Youtube site
4. Step #3: Login with a username and password
5. Step #4: Enter a search term
6. Step #5: Click on a video
7. Step #6: Enter a comment
8. Step #7: Go back
9. Step #8: Put it all together
10. Source Code
11. Conclusion
12. More Interesting Articles

https://www.hellocodeclub.com/youtube-comment-bot 1/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

Overview
Our Youtube bot will simulate being a regular user. It will open the browser, log in on youtube and enter
any search term you like on the search area. Then it will start opening each of the resulting videos, leave a
message and go back and click on another video, just like a user would do.

When running a selenium bot against a site like Youtube, it’s important to simulate human behavior to
avoid being detected and banned. Therefore, adding pauses when typing or clicking is crucial to
replicating what a user would do.

However, unlike an actual person, the bot doesn’t get tired and will keep writing messages for as long as
you wish. And for as long as It goes undetected. Let’s see step by step how to program the bot to carry on
this task.

Step #1: Install Selenium


Defn:pip :pip is a package manger that comes with python
and can be used with both Windows and Linux by just
typing pip install in the terminal.
The first step to build a Python Youtube comment bot is installing the selenium library. You can install
the library using the pip tool, which manages all python installed libraries.

You can install selenium executing the following command from your terminal:

1 pip install selenium

To use selenium you also need a driver, which is basically a browser. You could just use your already
installed browser or download a driver. I would recommend downloading a driver to avoid messing up
your browser settings. You can download a driver following the link below:

Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox: https://github.com/mozilla/geckodriver/releases
Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

Make a note where you save this file, you will need it in the following steps.

Step #2: Open Youtube site


By now, you should have selenium installed and the driver file. Time to start adding some code to our bot.
The first step is opening the youtube site: www.youtube.com. To open youtube with your bot, you will
need to create a new python script and add the following code:

1 from selenium import webdriver


2
3 browser = webdriver.Chrome('./chromedriver')
4 browser.get("https://www.youtube.com")

Please note that your python script and the chrome driver file should be in the same folder.

https://www.hellocodeclub.com/youtube-comment-bot 2/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

Step #3: Login with a username and password


The next step is signing in to Youtube. Signing in consists of five simple tasks:

Typing your email


Clicking next
Typing the password
Click next
Sometimes clicking on confirm, although this step is not always needed.

https://www.hellocodeclub.com/youtube-comment-bot 3/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

In the code snippet below, we define a function that will carry out all actions above in our bot browser.
We will paste this code in our bot script between the imports line, the first line, and line 3.

.login_with_username_and_password() function

1 def login_with_username_and_password(browser, username, password):


2
3    # Type email
4    email_input = browser.find_element_by_css_selector('input[type=email]')
5
6    email = username
7    for letter in email:
8        email_input.send_keys(letter)
9        wait_time = random.randint(0,1000)/1000
10        time.sleep(wait_time)
11
12    # Click next
13    next_button = browser.find_elements_by_css_selector("button")
14    time.sleep(2)
15    next_button[2].click()
16    time.sleep(2)
17
18    # Type password
19    password_input = browser.find_elements_by_css_selector('input[type=password]')
20    password = password
21    for letter in password:
22        password_input.send_keys(letter)
23        wait_time = random.randint(0,1000)/1000
24        time.sleep(wait_time)

https://www.hellocodeclub.com/youtube-comment-bot 4/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

25
26    # Click next
27    next_button = browser.find_elements_by_css_selector("button")
28    time.sleep(2)
29    next_button[1].click()
30
31    # Click Confirm
32    confirm_button = browser.find_elements_by_css_selector("div[role=button]")
33    time.sleep(2)
34    if(len(confirm_button)>0):
35        confirm_button[1].click()

The code above will first allocate the target component using a CSS selector. In Selenium you can do so
using two functions:

browser.find_elements_by_css_selector('')
browser.find_element_by_css_selector('')

The critical difference between these two methods is that the first method returns a list containing all
elements in the DOM document matching the CSS Selector. However, the second method only returns
one element, the first matching element.

Once we have located our target component, we can perform an action like clicking, sliding, typing, etc.
In this tutorial, we will mostly click and type.

To click we will use the .click() method:

1 next_button = browser.find_elements_by_css_selector("button")
2 next_button[2].click()

And to type we will use the .send_keys() method:

1 password_input = browser.find_elements_by_css_selector('input[type=password]')
2 password_input.send_keys("any string can go here")
3

Step #4: Enter a search term


Next, we define how to enter a search term into the search box. To do so, we will create a function
passing in the browser and the search term. You can paste this function in your python script under the
previous function.

https://www.hellocodeclub.com/youtube-comment-bot 5/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

.enter_search_term() function

1 def enter_search_term(browser,search_term):
2    # Enter text on the search term
3    search_input = browser.find_element_by_id("search")
4    for letter in search_term:
5        search_input.send_keys(letter)
6        wait_time = random.randint(0,1000)/1000
7        time.sleep(wait_time)
8
9    search_input.send_keys(Keys.ENTER)

As mentioned in the previous step, we will first locate the search input component in the DOM
document. In this instance, we will use the method .find_element_by_id("search") passing as argument
the id of the target component:

1 search_input = browser.find_element_by_id("search")

And then enter the search term, letter by letter using the method .send_keys():

1 for letter in search_term:


2 search_input.send_keys(letter)
https://www.hellocodeclub.com/youtube-comment-bot 6/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

3    # Quick pause between letter to replicate human behavior


4    wait_time = random.randint(0,1000)/1000
5    time.sleep(wait_time)

Step #5: Click on a video


After entering our search term, youtube will display a list of video suggestions based on our search.
Therefore all we need to do at this point is selecting one of the videos and click. We could select one
random video, or alternately select the first one, and follow the list order.

1 thumbnails = browser.find_elements_by_css_selector("ytd-video-renderer")
2
3    for index in range(1,6):
4        thumbnails[index].click()

In the code snippet above, we use the .find_elements_by_css_selector() method to select all videos listed
on the page. And then, starting on the first one, click sequentially on each video.

Step #6: Enter a comment


Finally, the crucial step, entering a comment. Once our browser opens the video page, we can insert our
comment. To enter a comment, we need to do the following:

Move to the comment input field


Click on the component, so it gets the focus.
Type our comment
Press the “Comment” button

https://www.hellocodeclub.com/youtube-comment-bot 7/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

In the code snippet, we define how to perform all the actions above:

First, finding the target element, in this case the comment input field.
Next we will group the next actions: move, click and type in an action chain, using the ActionChains
class.
And lastly our bot will click confirm.

.enter_comment() function

1 from selenium.webdriver.common.action_chains import ActionChains


2
3 def enter_comment(browser, comment):
4    comment_input = browser.find_element_by_css_selector("ytd-comment-simplebox-
renderer")
5
6    entering_comment_actions = ActionChains(browser)
7
https://www.hellocodeclub.com/youtube-comment-bot 8/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

8    entering_comment_actions.move_to_element(comment_input)
9    entering_comment_actions.click()
10
11    for letter in comment:
12        entering_comment_actions.send_keys(letter)
13        wait_time = random.randint(0,1000)/1000
14        entering_comment_actions.pause(wait_time)
15
16    entering_comment_actions.perform()
17
18    time.sleep(1)
19
20    send_comment_button = browser.find_element_by_id("submit-button")
21    send_comment_button.click()

As before, in order to closely mimic human behaviour, we will insert a milliseconds pause after typing
each letter( line 13 and 14)

Step #7: Go back


So far our bot has opened a video and enter a comment. We will need to go back to the video list and
click on the next video. We can achieve that easily press the back button in the browser. In Selenium, we
can go back to the previous page using the following code:

1 browser.execute_script("window.history.go(-1)")

The code above will open the previous url in the browser history.

Step #8: Put it all together


At this point, we have some code in our bot script containing functions that will log in to youtube, enter a
search term in the search box and enter a comment. The last step is connecting all the pieces.

The code below utilizes all functions created above and will open youtube and log in. Then we will use a
set of search terms, and for each search term our bot will: enter the search term, and leave a comment on
the first five video listed. And lastly, it will close the browser. Please note you can find the
.click_on_agree_and_signin() function defined below.

1 browser = webdriver.Chrome('./chromedriver')
2 browser.get("https://www.youtube.com")
3
4 # Click Agree and Sing In
5 click_on_agree_and_signin(browser)
6
7 # Sign In
8 login_with_username_and_password(browser, "your_username_here", "your_password_here")
9
10 all_search_terms =['make money online','online marketing']
11 for search_term in all_search_terms:
https://www.hellocodeclub.com/youtube-comment-bot 9/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

12    enter_search_term(browser, search_term)
13    time.sleep(2)
14
15    thumbnails = browser.find_elements_by_css_selector("ytd-video-renderer")
16
17    for index in range(1,6):
18        thumbnails[index].click()
19        time.sleep(6)
20
21        enter_comment(browser,"your comment here")
22        browser.execute_script("window.history.go(-1)")
23        thumbnails = browser.find_elements_by_css_selector("ytd-video-renderer")
24
25
26 time.sleep(1)
27 browser.close()

.click_on_agree_and_signin() function

1 def click_on_agree_and_signin(browser):
2    agree_button= browser.find_element_by_css_selector('button')
3    time.sleep(2)
4    agree_button.click()
5
6    signin_buttons= browser.find_elements_by_css_selector('yt-button-renderer')
7    time.sleep(6) # Wait longer so the message pops up
8    while(len(signin_buttons)== 0):
9        signin_buttons= browser.find_elements_by_css_selector('yt-button-renderer')
10        time.sleep(1)
11
12    signin_buttons[1].click()

Source Code
Source code available here.

Conclusion
In conclusion, you learn how to build a youtube comment box using python and selenium in this tutorial.
We have covered all steps the bot should perform from login, then searching video, and then entering a
comment using selenium. Additionally, this tutorial provides excellent examples of using selenium to
automatically navigate a website, which you could apply to automate any other tedious browser task.

I hope you enjoy this article, and thank you so much for reading and supporting this blog!

https://www.hellocodeclub.com/youtube-comment-bot 10/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

More Interesting Articles


Automate Data Entry – How to Create a Selenium bot

Python Graph Implementation Exercise – Plan a delivery route

Cool things to do with Python – Youtube Downloads

https://www.hellocodeclub.com/youtube-comment-bot 11/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

https://www.hellocodeclub.com/youtube-comment-bot 12/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects,
data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to
understand. Many practical examples

https://www.hellocodeclub.com/youtube-comment-bot 13/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

https://www.hellocodeclub.com/youtube-comment-bot 14/15
3/12/23, 2:07 PM Hello Code - How To Build a Youtube Comment Bot with Python

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on
how to perform an interview. Code Example in Java


 
 

Copyright © Hello Code Club 2023

Blog en Español

Privacy Policy

https://www.hellocodeclub.com/youtube-comment-bot 15/15

You might also like