Rose
Rose

Reputation: 103

Download image using requests url problem

I use this code to download image:

import shutil
import requests
url = 'https://cdn.pixabay.com/photo/2017/09/25/11/55/cyberspace-2784907__340.jpg'

response = requests.get(url, stream=True)
with open('img.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response

and it works. But when i use this type of link it dont work:

https://somesite.net/tor/poster.php/AOtJBawmVb0w7aHCjX5JmSo86CHVNKCFCz,KxohMSXIwMTIzNDU2Nzg5QUJDREVGR0hJSktMTU44N9qmOjPfy3FR58Dkq2XIpKhcjA1UPqrHlqXnX0kVs32sOTRn5f1QmKifHaeJ3Lwm80fo2bLATNETW1jZzTA=

if i put it in a web explorer, it shows, what is the best way to approach this?

I don't get an error when the image is downloaded, the file just says is not supported and i cannot get it to open in windows:

https://i.imgur.com/I2CUZ2v.png

The link works: the link to image

Upvotes: 0

Views: 573

Answers (2)

Timsib Adnap
Timsib Adnap

Reputation: 541

The image may not be png image. Check the first few bytes to see if it is png or jpeg or anything else.

png: 89 50 4E 47 0D 0A 1A 0A

jpeg: FF D8 FF E0 00 10 4A 46 49 46 00 01 or FF D8 FF EE or FF D8 FF E1 ?? ?? 45 78 69 66 00 00

bmp: 42 4D

webp: 52 49 46 46 ?? ?? ?? ?? 57 45 42 50

where question marks (??) are random bytes.

Check this out for full list of file signatures and there offsets

Upvotes: 0

Oleksii Tambovtsev
Oleksii Tambovtsev

Reputation: 2844

Maybe you should try to add

response.raw.decode_content = True

before

shutil.copyfileobj(response.raw, out_file)

If it does not work, could you please specify your problem and add correct "non-working" image URL?

Upvotes: 1

Related Questions