
But you can use the python requests module only to implement it also like below source code. Above python source code use both the python requests and shutil module.# Copy the response stream raw data to local image file. # Set decode_content value to True, otherwise the downloaded image file's size will be zero.

Local_file = open('local_image.jpg', 'wb') # Open a local file with wb ( write binary ) permission. Resp = requests.get(image_url, stream=True) # Open the url image, set stream to True, this will return the stream content. After running the below python code, it will download the image and save it to a local file local_image.jpg. Run below example code in the above python interactive command console.Open a terminal, and run command python or python3 to enter the python interactive command console.Use Python requests Module To Implement Download Image From URL Example. > req = Request(url=image_url, headers=headers)ĥ486 2. # Send request with simulated User-Agent header. > local_file = open('local_image_1.jpg','wb') > from urllib.request import urlopen, Request So we should change the above source code to the below which can send the User-Agent header to the webserver then the HTTPS request can be completed successfully.This is because the web server rejects the HTTPS request sent from () method which does not provide a User-Agent header ( The () method does not send a User-Agent header to the webserver ). But you will find above source code will throw an error message : HTTP Error 403: Forbidden.

Raise HTTPError(req.full_url, code, msg, hdrs, fp) 'http', request, response, code, msg, hdrs)įile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 569, in errorįile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 503, in _call_chainįile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 649, in http_error_default With contextlib.closing(urlopen(url, data)) as fp:įile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 222, in urlopenįile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 531, in openįile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 641, in http_response > (image_url, 'local_image.jpg')įile "/Users/songzhao/opt/anaconda3/lib/python3.7/urllib/request.py", line 247, in urlretrieve

