Getting 401 when trying to retrieve image using urllib - Python 2.7
I have been working on a small script that grabs an image from a website however I have to be authenticated to get the image. Using the following code I am able to pull down the webpage however I am having trouble getting the image I get the following error.
File "/usr/lib/python2.7/urllib.py", line 386, in http_error_default raise IOError, ('http error', errcode, errmsg, headers) IOError: ('http error', 401, 'Not Authorized', )
I think it's that I'm not passing my cookie to urllib but I am passing to urllib2.
I have checked that I am able to pull images where authentication isn't required.
The code Im using is as follows,
import urllib, urllib2 opener = urllib2.build_opener() opener.addheaders.append(('Cookie','CookieValue')) urllib.urlretrieve("https://www.example.com/image.jpg", 'image.jpg')
I'm a bit of a noob so any help would be appreciated.
There are some issues with your code. First you create an urllib2 object , apply the cookie for the request object and after that you use an urlib object. The last object does not have any access to the urlib2 object, to the cookie....so this is the reason that you get 401. Not allowed.
In this case: This is a code that is working and is based on the urllib2.
import urllib2 opener = urllib2.build_opener() opener.addheaders.append(('walley','GA1.2.1786704263.1458131937')) responce = opener.open('http://graphics8.nytimes.com/images/2011/10/11/science/13recipehealth/13recipehealth-articleLarge-v2.jpg').read() with open('new_jpg', 'wb') as out: out.write(responce)