To save a URL picture in Python, you can use the urllib
module to download the image from the URL, and then save it to your local file system. Here’s an example code snippet that shows how to do this:
import urllib.request url = "https://example.com/image.jpg" filename = "image.jpg" urllib.request.urlretrieve(url, filename)
In this code, we first define the URL of the image that we want to download and save, and the name of the file that we want to save it as (filename
). We then use the urllib.request.urlretrieve()
function to download the image from the URL and save it to the specified filename.
We can do the same task using the requests
library as follows:
import requests url = "https://example.com/image.jpg" filename = "image.jpg" response = requests.get(url) with open(filename, "wb") as f: f.write(response.content)
In this code, we first define the URL of the image that we want to download and save, and the name of the file that we want to save it as (filename
). We then use the requests.get()
method to send a GET request to the URL and retrieve the image content.
Next, we open the file in write binary mode ("wb"
) using the open()
function, and use the write()
method to write the content of the response to the file. Finally, we close the file using the with
statement.