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
3
4 browser = webdriver.Firefox()
5
6 browser.get('https://www.instagram.com/')
7
8 sleep(5)
9
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()