Reputation: 647
I'm trying to download an image using Python but I got the error "HTTP Error 403: Forbidden". I have no clue what to do to solve the issue. Here is my code:
import urllib.request as req
imgurl ="http://www.example.com/image.jpg"
req.urlretrieve(imgurl, r"C:\Users\home\Desktop\images\image_name.jpg")
Upvotes: 0
Views: 61
Reputation: 11157
It appears that urllib
's default user agent is the culprit. If you change it to one of a traditional browser, it works:
>>> opener = req.build_opener()
>>> opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36')]
>>> req.install_opener(opener)
>>> req.urlretrieve(imgurl, r"img.jpg")
('img.jpg', <http.client.HTTPMessage object at 0x7f75aaf05a90>)
Upvotes: 1