Summary: In this tutorial, we will learn to download images from Instagram using Python.
Before proceeding, we must have selenium, requests, and BeautifulSoup libraries installed in our machine.
Enter the following commands one by one into the terminal and hit Enter to install them on your machine.
pip install selenium pip install requests pip install bs4
sudo pip3 install selenium sudo pip3 install requests sudo pip3 install bs4
The selenium library uses the chrome browser for web browsing which requires installing chrome drivers on our computers.
So I recommend you to download the version specific to your computer specification from here (Don’t worry driver file size is small :P).
Now as we have all the resources. Let’s write a script in python to download Instagram images from python.
Python Script to Download Instagram’s Images
#python script to download instagram image from bs4 import BeautifulSoup import requests from selenium import webdriver import time ''' ask user to input the instagram post url ''' link = input("Enter Instagram Image URL: ") ''' create a webdriver chrome object by passing the path of "chromedriver.exe" file.(do not include .exe in the path). ''' driver = webdriver.Chrome('chromedriver') ''' Open the instagram post on your chrome browser''' driver.get(link) ''' Fetch the source file of the html page using BeautifulSoup''' soup = BeautifulSoup(driver.page_source, 'lxml') ''' Extract the url of the image from the source code''' img = soup.find('img', class_='FFVAD') img_url = img['src'] '''Download the image via the url using the requests library''' r = requests.get(img_url) with open("instagram"+str(time.time())+".png",'wb') as f: f.write(r.content) print('success')
In the above program, we have used
time.time() in addition to generating unique numbers for our file name.
Every time we run the script, the downloaded image file will have a unique file name.
Where the Image is Saved?
In the above example,we are saving the image in the same directory where the python script is stored.
If you don’t know where your file is being downloaded or the path of your Python script then uses the following code in your program to print the path of your current script.
import os print(os.getcwd())
To save the file into some other directory then provide the full path of the image file to the
open() method as a parameter.
Why did we use Selenium?
Selenium captures the source code of the web page after all the rendering has been finished. Hence we get the complete HTML source file of the page, so forth the URL of the Instagram post’s image.
This Post Has 4 Comments
It is working Thank You 🙏
Please help, it’s not working,
Have you installed the selenium driver as well as the chrome browser?
how about the clarity of the images ? looks not very good.