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! Show 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:
You’ll begin by learning how Instagram bots work before you build one. Important: Make sure you check Instagram’s Terms of Use before implementing any kind of automation or scraping techniques. Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level. How Instagram Bots WorkHow 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 1, 2, or 3. 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:
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. Remove adsHow to Automate a BrowserFor 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 since the latest version of . 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:
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:
This is the Selenium version of 9. 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:
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:
Note the highlighted lines:
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:
Next, change the script so that it finds those elements, enters your credentials, and clicks on the login button:
Here’s a breakdown of the changes:
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 PatternNow that you’ve written the login code, how would you write a test for it? It would look something like the following:
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 6 class and a 7 class:
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 8. If you had another class called 9, then 0 of the 7 class would return an instance of that: 2.Here’s how you can put the Page Object Pattern to use:
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. Note: Both Selenium and the Page Object Pattern are widely used for other websites, not just for Instagram. How to Build an Instagram Bot With InstaPyIn 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:
This will install 3 in your system.Note: The best practice is to use virtual environments for every project so that the dependencies are isolated. Remove adsEssential FeaturesNow 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:
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:
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 4 or 5 using 6: 0Here, 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: 1By default, InstaPy will like the first nine top posts in addition to your 7 value. In this case, that brings the total number of likes per tag to fourteen (nine top posts plus the five you specified in 7).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 9: 2With this change, posts that have the words 0 or 1 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 2: 3If 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 3: 4Next, tell the bot what comments to leave with 4: 5Run 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 5: 6This will close the browser, save the logs, and prepare a report that you can see in the console output. Remove adsAdditional Features in InstaPyInstaPy 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 SupervisorYou 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: 7The bot will keep commenting until it reaches its hourly and daily limits. It will resume commenting after the quota period has passed. Headless BrowserThis 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: 8Note that you set this flag when you initialize the 6 object.Using AI to Analyze PostsEarlier 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: 9Now your bot won’t like or comment on any image that ClarifAI considers NSFW. You get 5,000 free API-calls per month. Relationship BoundsIt’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: 0With 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. ConclusionInstaPy 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:
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. You can also explore the possibilities of ChatterBot, Tweepy, Discord, and Alexa Skills to learn more about how you can make bots for different platforms using Python. If there’s anything you’d like to ask or share, then please reach out in the comments below. Mark as Completed 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. Send Me Python Tricks » About Jahongir Rahmonov Jahongir is a Software Engineer based in Berlin, originally from Uzbekistan. He loves to talk about Python, Django, GCP and Kubernetes. » More about JahongirEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Aldren Geir Arne Joanna Jacob Mike Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal. |