Automate Instagram Python

How to Make an Instagram Bot With Python and InstaPy

What do SocialCaptain, Kicksta, Instavast, and many other companies have in common? They all help you reach a greater audience, gain more followers, and get more likes on Instagram while you hardly lift a finger. They do it all through automation, and people pay them a good deal of money for it. But you can do the same thing—for free—using InstaPy!
In this tutorial, you’ll learn how to build a bot with Python and InstaPy, a library by Tim Großmann which automates your Instagram activities so that you gain more followers and likes with minimal manual input. Along the way, you’ll learn about browser automation with Selenium and the Page Object Pattern, which together serve as the basis for InstaPy.
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
You’ll begin by learning how Instagram bots work before you build one.
How Instagram Bots Work
How can an automation script gain you more followers and likes? Before answering this question, think about how an actual person gains more followers and likes.
They do it by being consistently active on the platform. They post often, follow other people, and like and leave comments on other people’s posts. Bots work exactly the same way: They follow, like, and comment on a consistent basis according to the criteria you set.
The better the criteria you set, the better your results will be. You want to make sure you’re targeting the right groups because the people your bot interacts with on Instagram will be more likely to interact with your content.
For example, if you’re selling women’s clothing on Instagram, then you can instruct your bot to like, comment on, and follow mostly women or profiles whose posts include hashtags such as #beauty, #fashion, or #clothes. This makes it more likely that your target audience will notice your profile, follow you back, and start interacting with your posts.
How does it work on the technical side, though? You can’t use the Instagram Developer API since it is fairly limited for this purpose. Enter browser automation. It works in the following way:
You serve it your credentials.
You set the criteria for who to follow, what comments to leave, and which type of posts to like.
Your bot opens a browser, types in on the address bar, logs in with your credentials, and starts doing the things you instructed it to do.
Next, you’ll build the initial version of your Instagram bot, which will automatically log in to your profile. Note that you won’t use InstaPy just yet.
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:
1from time import sleep
2from selenium import webdriver
3
4browser = refox()
5
(”)
7
8sleep(5)
9
()
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 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.
This is the Selenium version of Hello, World. Now you’re ready to add the code that logs in to your Instagram profile. But first, think about how you would log in to your profile manually. You would do the following:
Go to Click the login link.
Enter your credentials.
Hit the login button.
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:
plicitly_wait(5)
6
8
9login_link = nd_element_by_xpath(“//a[text()=’Log in’]”)
11
12sleep(5)
13
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.
On the login page, there are three important elements:
The username input
The password input
The login button
Next, change the script so that it finds those elements, enters your credentials, and clicks on the login button:
12sleep(2)
14username_input = nd_element_by_css_selector(“input[name=’username’]”)
15password_input = nd_element_by_css_selector(“input[name=’password’]”)
16
nd_keys(““)
nd_keys(““)
19
20login_button = nd_element_by_xpath(“//button[@type=’submit’]”)
22
23sleep(5)
24
Here’s a breakdown of the changes:
Line 12 sleeps for two seconds to allow the page to load.
Lines 14 and 15 find username and password inputs by CSS. You could use any other method that you prefer.
Lines 17 and 18 type your username and password in their respective inputs. Don’t forget to fill in and !
Line 20 finds the login button by XPath.
Line 21 clicks on the login button.
Run the script and you’ll be automatically logged in to to your Instagram profile.
You’re off to a good start with your Instagram bot. If you were to continue writing this script, then the rest would look very similar. You would find the posts that you like by scrolling down your feed, find the like button by CSS, click on it, find the comments section, leave a comment, and continue.
The good news is that all of those steps can be handled by InstaPy. But before you jump into using Instapy, there is one other thing that you should know about to better understand how InstaPy works: the Page Object Pattern.
How to Use the Page Object Pattern
Now that you’ve written the login code, how would you write a test for it? It would look something like the following:
def test_login_page(browser):
username_input = nd_element_by_css_selector(“input[name=’username’]”)
password_input = nd_element_by_css_selector(“input[name=’password’]”)
login_button = nd_element_by_xpath(“//button[@type=’submit’]”)
errors = nd_elements_by_css_selector(‘#error_message’)
assert len(errors) == 0
Can you see what’s wrong with this code? It doesn’t follow the DRY principle. That is, the code is duplicated in both the application and the test code.
Duplicating code is especially bad in this context because Selenium code is dependent on UI elements, and UI elements tend to change. When they do change, you want to update your code in one place. That’s where the Page Object Pattern comes in.
With this pattern, you create page object classes for the most important pages or fragments that provide interfaces that are straightforward to program to and that hide the underlying widgetry in the window. With this in mind, you can rewrite the code above and create a HomePage class and a LoginPage class:
from time import sleep
class LoginPage:
def __init__(self, browser):
owser = browser
def login(self, username, password):
nd_keys(username)
nd_keys(password)
sleep(5)
class HomePage:
def go_to_login_page(self):
nd_element_by_xpath(“//a[text()=’Log in’]”)()
sleep(2)
return LoginPage(owser)
The code is the same except that the home page and the login page are represented as classes. The classes encapsulate the mechanics required to find and manipulate the data in the UI. That is, there are methods and accessors that allow the software to do anything a human can.
One other thing to note is that when you navigate to another page using a page object, it returns a page object for the new page. Note the returned value of go_to_log_in_page(). If you had another class called FeedPage, then login() of the LoginPage class would return an instance of that: return FeedPage().
Here’s how you can put the Page Object Pattern to use:
from selenium import webdriver
browser = refox()
home_page = HomePage(browser)
login_page = home_page. go_to_login_page()
(““, ““)
It looks much better, and the test above can now be rewritten to look like this:
With these changes, you won’t have to touch your tests if something changes in the UI.
For more information on the Page Object Pattern, refer to the official documentation and to Martin Fowler’s article.
Now that you’re familiar with both Selenium and the Page Object Pattern, you’ll feel right at home with InstaPy. You’ll build a basic bot with it next.
How to Build an Instagram Bot With InstaPy
In this section, you’ll use InstaPy to build an Instagram bot that will automatically like, follow, and comment on different posts. First, you’ll need to install InstaPy:
$ python3 -m pip install instapy
This will install instapy in your system.
Essential Features
Now you can rewrite the code above with InstaPy so that you can compare the two options. First, create another Python file and put the following code in it:
from instapy import InstaPy
InstaPy(username=”“, password=”“)()
Replace the username and password with yours, run the script, and voilà! With just one line of code, you achieved the same result.
Even though your results are the same, you can see that the behavior isn’t exactly the same. In addition to simply logging in to your profile, InstaPy does some other things, such as checking your internet connection and the status of the Instagram servers. This can be observed directly on the browser or in the logs:
INFO [2019-12-17 22:03:19] [username] — Connection Checklist [1/3] (Internet Connection Status)
INFO [2019-12-17 22:03:20] [username] – Internet Connection Status: ok
INFO [2019-12-17 22:03:20] [username] – Current IP is “17. 283. 46. 379” and it’s from “Germany/DE”
INFO [2019-12-17 22:03:20] [username] — Connection Checklist [2/3] (Instagram Server Status)
INFO [2019-12-17 22:03:26] [username] – Instagram WebSite Status: Currently Up
Pretty good for one line of code, isn’t it? Now it’s time to make the script do more interesting things than just logging in.
For the purpose of this example, assume that your profile is all about cars, and that your bot is intended to interact with the profiles of people who are also interested in cars.
First, you can like some posts that are tagged #bmw or #mercedes using like_by_tags():
1from instapy import InstaPy
2
3session = InstaPy(username=”“, password=”“)
ke_by_tags([“bmw”, “mercedes”], amount=5)
Here, you gave the method a list of tags to like and the number of posts to like for each given tag. In this case, you instructed it to like ten posts, five for each of the two tags. But take a look at what happens after you run the script:
INFO [2019-12-17 22:15:58] [username] Tag [1/2]
INFO [2019-12-17 22:15:58] [username] –> b’bmw’
INFO [2019-12-17 22:16:07] [username] desired amount: 14 | top posts [disabled]: 9 | possible posts: 43726739
INFO [2019-12-17 22:16:13] [username] Like# [1/14]
INFO [2019-12-17 22:16:13] [username] INFO [2019-12-17 22:16:15] [username] Image from: b’mattyproduction’
INFO [2019-12-17 22:16:15] [username] Link: b”
INFO [2019-12-17 22:16:15] [username] Description: b’Mal etwas anderes \xf0\x9f\x91\x80\xe2\x98\xba\xef\xb8\x8f Bald ist das komplette Video auf YouTube zu finden (n\xc3\xa4here Infos werden folgen). Vielen Dank an @patrick_jwki @thehuthlife und @christic_ f\xc3\xbcr das bereitstellen der Autos \xf0\x9f\x94\xa5\xf0\x9f\x98\x8d#carporn#cars#tuning#bagged#bmw#m2#m2competition#focusrs#ford#mk3#e92#m3#panasonic#cinematic#gh5s#dji#roninm#adobe#videography#music#bimmer#fordperformance#night#shooting#’
INFO [2019-12-17 22:16:15] [username] Location: b’K\xc3\xb6ln, Germany’
INFO [2019-12-17 22:16:51] [username] –> Image Liked!
INFO [2019-12-17 22:16:56] [username] –> Not commented
INFO [2019-12-17 22:16:57] [username] –> Not following
INFO [2019-12-17 22:16:58] [username] Like# [2/14]
INFO [2019-12-17 22:16:58] [username] INFO [2019-12-17 22:17:01] [username] Image from: b’davs0′
INFO [2019-12-17 22:17:01] [username] Link: b”
INFO [2019-12-17 22:17:01] [username] Description: b’Someone said cloud? \xf0\x9f\xa4\x94\xf0\x9f\xa4\xad\xf0\x9f\x98\x88 \xe2\x80\xa2\n\xe2\x80\xa2\n\xe2\x80\xa2\n\xe2\x80\xa2\n#bmw #bmwrepost #bmwm4 #bmwm4gts #f82 #bmwmrepost #bmwmsport #bmwmperformance #bmwmpower #bmwm4cs #austinyellow #davs0 #mpower_official #bmw_world_ua #bimmerworld #bmwfans #bmwfamily #bimmers #bmwpost #ultimatedrivingmachine #bmwgang #m3f80 #m5f90 #m4f82 #bmwmafia #bmwcrew #bmwlifestyle’
INFO [2019-12-17 22:17:34] [username] –> Image Liked!
INFO [2019-12-17 22:17:37] [username] –> Not commented
INFO [2019-12-17 22:17:38] [username] –> Not following
By default, InstaPy will like the first nine top posts in addition to your amount value. In this case, that brings the total number of likes per tag to fourteen (nine top posts plus the five you specified in amount).
Also note that InstaPy logs every action it takes. As you can see above, it mentions which post it liked as well as its link, description, location, and whether the bot commented on the post or followed the author.
You may have noticed that there are delays after almost every action. That’s by design. It prevents your profile from getting banned on Instagram.
Now, you probably don’t want your bot liking inappropriate posts. To prevent that from happening, you can use set_dont_like():
session = InstaPy(username=”“, password=”“)
t_dont_like([“naked”, “nsfw”])
With this change, posts that have the words naked or nsfw in their descriptions won’t be liked. You can flag any other words that you want your bot to avoid.
Next, you can tell the bot to not only like the posts but also to follow some of the authors of those posts. You can do that with set_do_follow():
t_do_follow(True, percentage=50)
If you run the script now, then the bot will follow fifty percent of the users whose posts it liked. As usual, every action will be logged.
You can also leave some comments on the posts. There are two things that you need to do. First, enable commenting with set_do_comment():
t_do_comment(True, percentage=50)
Next, tell the bot what comments to leave with set_comments():
t_comments([“Nice! “, “Sweet! “, “Beautiful:heart_eyes:”])
Run the script and the bot will leave one of those three comments on half the posts that it interacts with.
Now that you’re done with the basic settings, it’s a good idea to end the session with end():
This will close the browser, save the logs, and prepare a report that you can see in the console output.
Additional Features in InstaPy
InstaPy is a sizable project that has a lot of thoroughly documented features. The good news is that if you’re feeling comfortable with the features you used above, then the rest should feel pretty similar. This section will outline some of the more useful features of InstaPy.
Quota Supervisor
You can’t scrape Instagram all day, every day. The service will quickly notice that you’re running a bot and will ban some of its actions. That’s why it’s a good idea to set quotas on some of your bot’s actions. Take the following for example:
t_quota_supervisor(enabled=True, peak_comments_daily=240, peak_comments_hourly=21)
The bot will keep commenting until it reaches its hourly and daily limits. It will resume commenting after the quota period has passed.
Headless Browser
This feature allows you to run your bot without the GUI of the browser. This is super useful if you want to deploy your bot to a server where you may not have or need the graphical interface. It’s also less CPU intensive, so it improves performance. You can use it like so:
session = InstaPy(username=’test’, password=’test’, headless_browser=True)
Note that you set this flag when you initialize the InstaPy object.
Using AI to Analyze Posts
Earlier you saw how to ignore posts that contain inappropriate words in their descriptions. What if the description is good but the image itself is inappropriate? You can integrate your InstaPy bot with ClarifAI, which offers image and video recognition services:
t_use_clarifai(enabled=True, api_key=’‘)
arifai_check_img_for([‘nsfw’])
Now your bot won’t like or comment on any image that ClarifAI considers NSFW. You get 5, 000 free API-calls per month.
Relationship Bounds
It’s often a waste of time to interact with posts by people who have a lot of followers. In such cases, it’s a good idea to set some relationship bounds so that your bot doesn’t waste your precious computing resources:
t_relationship_bounds(enabled=True, max_followers=8500)
With this, your bot won’t interact with posts by users who have more than 8, 500 followers.
For many more features and configurations in InstaPy, check out the documentation.
Conclusion
InstaPy allows you to automate your Instagram activities with minimal fuss and effort. It’s a very flexible tool with a lot of useful features.
In this tutorial, you learned:
How to use the Page Object Pattern to make your code more maintainable and testable
How to use InstaPy to build a basic Instagram bot
Read the InstaPy documentation and experiment with your bot a little bit. Soon you’ll start getting new followers and likes with a minimal amount of effort. I gained a few new followers myself while writing this tutorial. If you prefer video tutorials, there is also a Udemy course by the creator of InstaPy Tim Großmann.
If there’s anything you’d like to ask or share, then please reach out in the comments below.
Automating Instagram Posts with Python and Instagram Graph ...

Automating Instagram Posts with Python and Instagram Graph …

You can now schedule your instagram posts programmatically without relying on limiting and expensive apps like Hootsuite and Later. You can create your own code to post to instagram up to 25 posts a day using the Instagram Graph nnect your facebook page to your instagram accountCreate facebook developer account and generate access tokens for Instagram APIGet your instagram graph API user ID for your instagram pagePublish an image to your instagram pagePython code for publishing an imageBefore we get started, it is important to note that you can only ever schedule posts for an instagram business account, not a personal account. An influencer account is accepted as a business account, you need to set this up from the instagram to your profile > Click on the hamburger menu at the top right > click on settings right at the bottom > and select account > scroll to the bottom and you will see an option to switch to business / professional account. Go through the steps and you are in to your facebook page, go to settings > instagram. You should see something like below:If you don’t see this, there will be a button that allows you to connect the facebook page to an instagram account. Before you click on the button, it helps if you already have instagram logged in another window — browser has a cookie. You will be able to just connect that account, re-enter your password and you are is similar to what we did in the tutorial: graph API access keys can be found in the same place as the facebook graph API keys, in fact you can use the same application that was created to post to facebook to generate the tokens — you just have to adjust the access rights. These are the access rights you need to add:Visit: to add permissions to your app. Make sure you select the correct app from the dropdown if you have more than one are all the permissions you will now have after adding the instagram permissions:pages_show_listinstagram_basicinstagram_manage_commentsinstagram_manage_insightsinstagram_content_publishpages_read_engagementpages_manage_postspublic_profileAfter you have added these permissions, click on Generate access token and you will go through the login process for both the facebook page and instagram page — the first the access token you get from Graph API explorer is a short life token — only valid for an hour, you need to exchange this token with a long life token valid for 60days. You need the USER access token for instagram the command below:curl -i -X GET “graph-api-version}/oauth/access_token? grant_type=fb_exchange_token& client_id={app-id}& client_secret={app-secret}& fb_exchange_token={your-access-token}”You will need your: (1) App ID, (2) App secret and (3) Short life access token for this request. If successful, you will receive a long life token in requests to the instagram graph API require a page user ID, you can get it easily using the user access token from above and the facebook page ID. The facebook page ID can be found from the about section of the facebook page you connected to the instagram account at the beginning of this -i -X GET \ “facebook_page_id}? fields=instagram_business_account&access_token={access-token}”That is it, you can now send posts directly to instagram using the are sent to instagram in a two step process: (1) You create a container with the image, instagram returns you a creation id, (2) you publish the creation id to send the post to All requests need your user access token (preferably the long life token) -i -X POST ig_user_id}/media? image_url={public__path_to_image}&caption={url_encoded_caption}&access_token={user_access_token}What you need for this request is:IG user ID from section abovePath to image you want to post (ideally square image for IG and the path must be publicly accesible, like or server)URL encoded captionUser access tokenThen send the post using the creation id you will receive:POST ig_user_id}/media_publish? creation_id={creation_id}&access_token={user_access_token}The fun begins, it would take way too much effort to go though all these steps just to post one image. The power of python is the ability to pre-schedule posts in advance, even create posts on the fly using html, the possibilities are endless:import requestsimport configimport jsondef postInstagramQuote():#Post the Image image_location_1 = ” post_url = ‘}/media'(config. ig_user_id)payload = { ‘image_url’: image_location_1, ‘caption’: ‘Get jobs online on #career #hiring #jobs #job #jobssouthafrica #hiringnow, ‘access_token’: er_access_token} r = (post_url, data=payload) print()result = () if ‘id’ in result: creation_id = result[‘id’]second_url = ‘}/media_publish'(config. ig_user_id) second_payload = { ‘creation_id’: creation_id, ‘access_token’: er_access_token} r = (second_url, data=second_payload) print(‘——–Just posted to instagram——–‘) print() else: print(‘HOUSTON we have a problem’)postInstagramQuote()Subsequently, you can use the python schedule library to schedule these posts more, watch our youtube tutorial where we take it a step further to create actual images using python and imgkit from HTML, so you can create fresh content daily for instagram using tube Instagram automation tutorial with Instagram Graph API and Python
Automating Instagram Posts with Python and Instagram Graph ...

Automating Instagram Posts with Python and Instagram Graph …

You can now schedule your instagram posts programmatically without relying on limiting and expensive apps like Hootsuite and Later. You can create your own code to post to instagram up to 25 posts a day using the Instagram Graph nnect your facebook page to your instagram accountCreate facebook developer account and generate access tokens for Instagram APIGet your instagram graph API user ID for your instagram pagePublish an image to your instagram pagePython code for publishing an imageBefore we get started, it is important to note that you can only ever schedule posts for an instagram business account, not a personal account. An influencer account is accepted as a business account, you need to set this up from the instagram to your profile > Click on the hamburger menu at the top right > click on settings right at the bottom > and select account > scroll to the bottom and you will see an option to switch to business / professional account. Go through the steps and you are in to your facebook page, go to settings > instagram. You should see something like below:If you don’t see this, there will be a button that allows you to connect the facebook page to an instagram account. Before you click on the button, it helps if you already have instagram logged in another window — browser has a cookie. You will be able to just connect that account, re-enter your password and you are is similar to what we did in the tutorial: graph API access keys can be found in the same place as the facebook graph API keys, in fact you can use the same application that was created to post to facebook to generate the tokens — you just have to adjust the access rights. These are the access rights you need to add:Visit: to add permissions to your app. Make sure you select the correct app from the dropdown if you have more than one are all the permissions you will now have after adding the instagram permissions:pages_show_listinstagram_basicinstagram_manage_commentsinstagram_manage_insightsinstagram_content_publishpages_read_engagementpages_manage_postspublic_profileAfter you have added these permissions, click on Generate access token and you will go through the login process for both the facebook page and instagram page — the first the access token you get from Graph API explorer is a short life token — only valid for an hour, you need to exchange this token with a long life token valid for 60days. You need the USER access token for instagram the command below:curl -i -X GET “graph-api-version}/oauth/access_token? grant_type=fb_exchange_token& client_id={app-id}& client_secret={app-secret}& fb_exchange_token={your-access-token}”You will need your: (1) App ID, (2) App secret and (3) Short life access token for this request. If successful, you will receive a long life token in requests to the instagram graph API require a page user ID, you can get it easily using the user access token from above and the facebook page ID. The facebook page ID can be found from the about section of the facebook page you connected to the instagram account at the beginning of this -i -X GET \ “facebook_page_id}? fields=instagram_business_account&access_token={access-token}”That is it, you can now send posts directly to instagram using the are sent to instagram in a two step process: (1) You create a container with the image, instagram returns you a creation id, (2) you publish the creation id to send the post to All requests need your user access token (preferably the long life token) -i -X POST ig_user_id}/media? image_url={public__path_to_image}&caption={url_encoded_caption}&access_token={user_access_token}What you need for this request is:IG user ID from section abovePath to image you want to post (ideally square image for IG and the path must be publicly accesible, like or server)URL encoded captionUser access tokenThen send the post using the creation id you will receive:POST ig_user_id}/media_publish? creation_id={creation_id}&access_token={user_access_token}The fun begins, it would take way too much effort to go though all these steps just to post one image. The power of python is the ability to pre-schedule posts in advance, even create posts on the fly using html, the possibilities are endless:import requestsimport configimport jsondef postInstagramQuote():#Post the Image image_location_1 = ” post_url = ‘}/media'(config. ig_user_id)payload = { ‘image_url’: image_location_1, ‘caption’: ‘Get jobs online on #career #hiring #jobs #job #jobssouthafrica #hiringnow, ‘access_token’: er_access_token} r = (post_url, data=payload) print()result = () if ‘id’ in result: creation_id = result[‘id’]second_url = ‘}/media_publish'(config. ig_user_id) second_payload = { ‘creation_id’: creation_id, ‘access_token’: er_access_token} r = (second_url, data=second_payload) print(‘——–Just posted to instagram——–‘) print() else: print(‘HOUSTON we have a problem’)postInstagramQuote()Subsequently, you can use the python schedule library to schedule these posts more, watch our youtube tutorial where we take it a step further to create actual images using python and imgkit from HTML, so you can create fresh content daily for instagram using tube Instagram automation tutorial with Instagram Graph API and Python

Frequently Asked Questions about automate instagram python

Can you automate Instagram posts with Python?

You can now schedule your instagram posts programmatically without relying on limiting and expensive apps like Hootsuite and Later. You can create your own code to post to instagram up to 25 posts a day using the Instagram Graph API.Mar 29, 2021

How do you automate Instagram messages in Python?

Automate Instagram Messages using PythonStep 1: Importing all the necessary libraries.Step 2: Using chrome with this code will always work (no need to worry about updating chromedriver version)Step 3: Before declaring a Class we will make a list of users( any no.More items…•Nov 1, 2020

Can I automate my Instagram?

Instagram automation is the process of using third-party software and apps to manage your Instagram account. This could mean scheduling posts, liking, commenting, reporting, and more. Instagram automation is typically done via the use of bots.Apr 22, 2021

Leave a Reply

Your email address will not be published. Required fields are marked *