In this post, let us look at how to download Instagram profile pictures using python.
Everyone nowadays utilizes social media, and one of the most popular apps is Instagram. Its users enjoy its material, which includes text, effects, stickers, and so on. One of them is the video and reel feature.
Web scraping is a task that needs an understanding of how web pages are structured. To obtain the required information from web pages, one must first understand the structure of the web pages, then analyze the tags that contain the required information, and finally the attributes of those tags.
It is intended for programmers, data analysts, scientists, and engineers who are already proficient in extracting content from web pages with BeautifulSoup.
You may have noticed that there are numerous websites that are both complex and lengthy, making it difficult to find anything. Python includes some built-in libraries to help us with searching, modifying, and iterating, such as Requests, Xml, Beautiful Soup, Selenium, Scrapy, and so on.
Python Requests
To understand how the requests module works, you must first understand what happens when you browse the web and how it instantaneously displays the data we were hoping to see.
When you click a link, we make an HTTP (Hypertext Transfer Protocol) request to the server that hosts the requested page.
When the server receives the request, it returns the requested content to us.
The two most useful HTTP requests are GET and POST.
Python Code to Download Instagram profile pic
Method #1: Using instaloader Module
Python and the PyCharm IDE must be installed on your computer (or you can use any of your IDE)
We can use the instaloader module to download the profile picture of any Instagram account by simply entering the user’s Instagram handle.
Type the below command to install the instaloader module:
pip install instaloader
Output:
Looking in indexes: Collecting instaloader Downloading instaloader-4.9.3.tar.gz (60 kB) |████████████████████████████████| 60 kB 2.7 MB/s Requirement already satisfied: requests>=2.4 in /usr/local/lib/ python3.7/dist-packages (from instaloader) (2.23.0) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.4->instaloader) (3.0.4) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.4->instaloader) (2.10) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/ dist-packages (from requests>=2.4->instaloader) (1.24.3) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/ dist-packages (from requests>=2.4->instaloader) (2022.6.15) Building wheels for collected packages: instaloader Building wheel for instaloader (setup.py) ... done Created wheel for instaloader: filename=instaloader-4.9.3-py3-none-any.whl size=62303 sha256=eaecaa74aa9702c5841e4f698afa7e357a59823c20816bb5dfad4f7193ec40a6 Stored in directory: /root/.cache/pip/wheels/38/d0/76/393aa35939 4d16f2744f5bf8cb71cddb68ad8944de7722a4bd Successfully built instaloader Installing collected packages: instaloader Successfully installed instaloader-4.9.3
Approach:
- Import instaloader module using the import keyword
- Give the instagram user name as user input using the input() function and store it in a variable
- Download the instagram profile picture using the download_profile() function by passing the above insta username, profile_pic_only as True as arguments to it.
- Print some random text for acknowledgment.
- The Exit of the Program.
Below is the implementation:
# Import instaloader module using the import keyword import instaloader # Give the insta user name as user input using the input() function and # store it in a variable instagramUsername = input("Enter some random instagram username = ") # Download the instagram profile picture using the download_profile() function # by passing the above insta username, profile_pic_only as True as arguments to it instaloader.Instaloader().download_profile(instagramUsername , profile_pic_only=True) # Print some random text for acknowledgment print("The instagram profile picture is download succesfully!!")
Output:
The instagram profile picture is download succesfully!!
Method #2: Using BeautifulSoup Module
Beautiful Soup, out of all the available Python libraries, is the one that performs web scraping relatively faster than the others. There are times when we need to use Beautiful Soup to find all of the children of a certain element.
Approach:
- Import requests, BeautifulSoup, json, random and os.path modules using the import keyword.
- Give the website URL of instagram and store it in a variable.
- Give the instagram username as user input using the input() function and store it in another variable.
- Get the response using the requests module get() function.
- Check if the response is success(here ok attribute specifies request is success).
- Get the text of the response using the text attribute and save it in a variable.
- Create a random file name to store using the random function and save it in a variable (here .jpg specifies image extension).
- Check if the above file exists in our system using the isfile() function.
- If the file doesn’t exists then we can save with the above filename.
- Open the above file in the write binary mode.
- Get the response from the string url using the requests module get() function.
- If we get in any error then we print the error.
- Else we write the image to the file using the write() function.
- The Exit of the Program.
Below is the implementation:
# Import requests, BeautifulSoup, json, random and # os.path modules using the import keyword import requests from bs4 import BeautifulSoup as bs import json import random import os.path # Give the website URL of instagram and store it in a variable instagramUrl='https://www.instagram.com' # Give the insta username as user input using the input() function and # store it in another variable instagramUsername= input("Enter some random instagram username =") # Get the response using the requests module get() function response = requests.get(f"{instagramUrl}/{instagramUsername}/") # Check if the response is success(here ok attribute specifies request is success) if response.ok: # Get the text of the response using the text attribute and save in a variable html=response.text bs_html=bs(html, features="lxml") bs_html=bs_html.text index=bs_html.find('profile_pic_url_hd')+21 remaining_text=bs_html[index:] remaining_text_index=remaining_text.find('requested_by_viewer')-3 string_url=remaining_text[:remaining_text_index].replace("\\u0026","&") print(string_url, "\n \n downloading..........") while True: # Create a random file name to store using the random function and save it in a variable (here .jpg specifies image extension) filename='pic'+str(random.randint(1, 100000))+'.jpg' # Check if the above file exists in our system using the isfile() function file_exists = os.path.isfile(filename) # If the file doesn't exists then we can save with the above filename if not file_exists: # Open the above file in the write binary mode with open(filename, 'wb+') as handle: # Get the response from the string url using the requests module get() function response = requests.get(string_url, stream=True) # If we get in any error then we print the error if not response.ok: print(response) # Else we write the image to the file using the write() function for block in response.iter_content(1024): if not block: break handle.write(block) else: continue break print("The instagram profile picture is download succesfully!!")
Output:
Enter some random instagram username = virat.kohli The instagram profile picture is download succesfully!!
Image: