In this tutorial, you’ll learn:


* How Instagram bots work
* How to automate a browser with Selenium
* How to use the Page Object Pattern for better readability and testability
* How to build an Instagram bot with InstaPy

How to Automate a Browser

For this version of your Instagram bot, you’ll be using Selenium, which is the tool that InstaPy uses under the hood.

First, install Selenium. During installation, make sure you also install the Firefox WebDriver since the latest version of InstaPy dropped support for Chrome. This also means that you need the Firefox browser installed on your computer.

Now, create a Python file and write the following code in it:

 1 from time import sleep
 2  from selenium import webdriver

browser = webdriver.Firefox()

browser.get('https://www.instagram.com/')

sleep(5)

10 browser.close()

Run the code and you’ll see that a Firefox browser opens and directs you to the Instagram login page. Here’s a line-by-line breakdown of the code:

Lines 1 and 2 import sleep and webdriver.

Line 4 initializes the Firefox driver and sets it to browser.

Line 6 types https://www.instagram.com/ on the address bar and hits Enter.

Line 8 waits for five seconds so you can see the result. Otherwise, it would close the browser instantly.

Line 10 closes the browser.

The first step is already done by the code above. Now change it so that it clicks on the login link on the Instagram home page:

The first step is already done by the code above. Now change it so that it clicks on the login link on the Instagram home page:


  1 from time import sleep
 2 from selenium import webdriver
 3
 4 browser = webdriver.Firefox()
 5 browser.implicitly_wait(5)
 6
 7 browser.get('https://www.instagram.com/')
 8
 9 login_link = browser.find_element_by_xpath("//a[text()='Log in']")
10 login_link.click()
11
12 sleep(5)
13
14 browser.close()

Note the highlighted lines:

Line 5 sets five seconds of waiting time. If Selenium can’t find an element, then it waits for five seconds to allow everything to load and tries again. Line 9 finds the element whose text is equal to Log in. It does this using XPath, but there are a few other methods you could use. Line 10 clicks on the found element for the login link. Run the script and you’ll see your script in action. It will open the browser, go to Instagram, and click on the login link to go to the login page.

Next, change the script so that it finds those elements, enters your credentials, and clicks on the login button:

Clik here to view Git Repo