DEV Community

Cover image for Create IMG file by a url link - Python

Posted on

Create IMG file by a url link - Python

Hey ! In this post, I'll show you how to create an IMG file, like a png or jpg file, with a url link in Python. Even if it seems difficult, it isn't !

The import :

Yeah for sure, we must to import a package that will scrap informations from the img link you want. And this package is : requests

Image description

So, let's go :

1) First open a new terminal and run the command :

pip install requests
Enter fullscreen mode Exit fullscreen mode

If it's not already installed.

2) Now create a new file, with the name you want and the .py

The script :

import requests, os
url = ""
with open("myIMG.png", "wb") as img_file:
    img = requests.get(url)
Enter fullscreen mode Exit fullscreen mode

So as you see, the script is 5 lines long. It's nothing !

First we import the package we installed before and the os package to open files.
Then, we open the file myIMG.jpg in write byte mode, and store it in img_file variable. The name and the extension of the img file can be modify for sure.

Inside the 'with', we make a request that get the content of the page from the url And after that, we simply write the content of this request in the file with the write method.

Summary :

As you see, to scrap an image and 'download' it by a python script isn't difficult. You just need of a package and a file where you write the content of the image you scraped.

If you want to know more about the requests package, check this out :

So nice to see you ! And see you in the next post. Bye bye 👋👨‍💻

Discussion (1)

umutarcn profile image
Umut A.

Thanks for the descriptive explanation.

Logo Source : Python Logo