Ahmed4end
Ahmed4end

Reputation: 324

requests fails to download any image from a certain site although all image there is downloadable?

Here is the code I use for downloading any image (it always works fine except for this site www.pexels.com) . It actually download the image, but corrupted when it comes to this site ? I wonder why ??

url = "https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"

response = requests.get(url , stream = True)

file= open("Hello.jpg" , 'wb')

for chunk in response.iter_content(10000):
    file.write(chunk)

file.close()

Upvotes: 3

Views: 1315

Answers (1)

BoreBoar
BoreBoar

Reputation: 2729

You need to add a user-agent to your request headers.

The following code works:

import requests

url = "https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
}
response = requests.get(url , stream = True, headers=headers)

file= open("Hello.jpg" , 'wb')

for chunk in response.iter_content(10000):
    file.write(chunk)

file.close()

Upvotes: 5

Related Questions