H
H
HEnl2020-06-11 19:58:16
Python
HEnl, 2020-06-11 19:58:16

What is the most efficient way to download a png image to hard drive from a python link?

I have tried the following way

import requests

img_url = 'http://markof.fun/im/1.png'
r = requests.get(img_url)
out = open('d:/o/temp.png', "wb")
out.write(r.content)
out.close()


As a result, it turns out like this:
5ee262a1dacb4498234063.png
But the picture is not recorded in any way. You just need to download the picture, and close it so that another program can use it. Is there an error in my code? Or how else to implement it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
soremix, 2020-06-11
@markbrutx

So you don’t have a picture if you make such a request. Server 403 returns. Check response status

import requests

img_url = 'http://markof.fun/im/1.png'

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
r = requests.get(img_url, headers=headers)

if r.status_code == 200:
    with open('temp.png', 'wb') as f:
        f.write(r.content)
else:
    print('Error', r.status_code)

D
Dimonchik, 2020-06-11
@dimonchik2013

https://stackoverflow.com/questions/13137817/how-t...

A
Alexander, 2020-06-11
@NeiroNx

from urllib.request import urlopen
with open("C:\\test.png","wb") as img,\
    urlopen("http://markof.fun/im/1.png") as data:
    img.write(data.read())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question