Posted by Marta on April 20, 2021 Viewed 28739 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!
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.
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:
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:
Make a note where you save this file, you will need it in the following steps.
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:
from selenium import webdriver browser = webdriver.Chrome('./chromedriver') browser.get("https://www.youtube.com")
Please note that your python script and the chrome driver file should be in the same folder.
The next step is signing in to Youtube. Signing in consists of five simple tasks:
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.
def login_with_username_and_password(browser, username, password): # Type email email_input = browser.find_element_by_css_selector('input[type=email]') email = username for letter in email: email_input.send_keys(letter) wait_time = random.randint(0,1000)/1000 time.sleep(wait_time) # Click next next_button = browser.find_elements_by_css_selector("button") time.sleep(2) next_button.click() time.sleep(2) # Type password password_input = browser.find_elements_by_css_selector('input[type=password]') password = password for letter in password: password_input.send_keys(letter) wait_time = random.randint(0,1000)/1000 time.sleep(wait_time) # Click next next_button = browser.find_elements_by_css_selector("button") time.sleep(2) next_button.click() # Click Confirm confirm_button = browser.find_elements_by_css_selector("div[role=button]") time.sleep(2) if(len(confirm_button)>0): confirm_button.click()
The code above will first allocate the target component using a CSS selector. In Selenium you can do so using two functions:
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
next_button = browser.find_elements_by_css_selector("button") next_button.click()
And to type we will use the
password_input = browser.find_elements_by_css_selector('input[type=password]') password_input.send_keys("any string can go here")
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.
def enter_search_term(browser,search_term): # Enter text on the search term search_input = browser.find_element_by_id("search") for letter in search_term: search_input.send_keys(letter) wait_time = random.randint(0,1000)/1000 time.sleep(wait_time) 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:
search_input = browser.find_element_by_id("search")
And then enter the search term, letter by letter using the method
for letter in search_term: search_input.send_keys(letter) # Quick pause between letter to replicate human behavior wait_time = random.randint(0,1000)/1000 time.sleep(wait_time)
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.
thumbnails = browser.find_elements_by_css_selector("ytd-video-renderer") for index in range(1,6): 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.
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:
In the code snippet, we define how to perform all the actions above:
from selenium.webdriver.common.action_chains import ActionChains def enter_comment(browser, comment): comment_input = browser.find_element_by_css_selector("ytd-comment-simplebox-renderer") entering_comment_actions = ActionChains(browser) entering_comment_actions.move_to_element(comment_input) entering_comment_actions.click() for letter in comment: entering_comment_actions.send_keys(letter) wait_time = random.randint(0,1000)/1000 entering_comment_actions.pause(wait_time) entering_comment_actions.perform() time.sleep(1) send_comment_button = browser.find_element_by_id("submit-button") 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)
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:
The code above will open the previous url in the browser history.
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.
browser = webdriver.Chrome('./chromedriver') browser.get("https://www.youtube.com") # Click Agree and Sing In click_on_agree_and_signin(browser) # Sign In login_with_username_and_password(browser, "your_username_here", "your_password_here") all_search_terms =['make money online','online marketing'] for search_term in all_search_terms: enter_search_term(browser, search_term) time.sleep(2) thumbnails = browser.find_elements_by_css_selector("ytd-video-renderer") for index in range(1,6): thumbnails[index].click() time.sleep(6) enter_comment(browser,"your comment here") browser.execute_script("window.history.go(-1)") thumbnails = browser.find_elements_by_css_selector("ytd-video-renderer") time.sleep(1) browser.close()
def click_on_agree_and_signin(browser): agree_button= browser.find_element_by_css_selector('button') time.sleep(2) agree_button.click() signin_buttons= browser.find_elements_by_css_selector('yt-button-renderer') time.sleep(6) # Wait longer so the message pops up while(len(signin_buttons)== 0): signin_buttons= browser.find_elements_by_css_selector('yt-button-renderer') time.sleep(1) signin_buttons.click()
Source code available here.
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!
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
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