1

The python code (python3)

import time
import urllib.response, requests

from config.dev import CONTENT_IMAGE_UPLOAD

directory = CONTENT_IMAGE_UPLOAD + "en_" + time.strftime('%Y%m%d')
filename =  "sample.jpg"
try:
    urllib.request.urlretrieve("https://www.miamiherald.com/latest-news/wfeh98/picture238148999/alternates/LANDSCAPE_1140/Screenshot%20(150).png", directory + "/" + filename)
    print("image is saved")
except Exception as e:
    print(e)

I am expecting to get the image in just less than one minute , but it take too long then print output as message like below.

[Errno 60] Operation timed out

I am sure the image is already exist because when I copied and pasted I got the image, but it seem the URL contains some special char in this part Screenshot%20(150).png,

How could I solve this error?

tree em
  • 20,379
  • 30
  • 92
  • 130

1 Answers1

2

You should add user agent to bypass this issue, I never use urllib directly I usually use requests as it's easier for me, you can implement the same concept using urllib if you want, but you will need to look that up, here's a sample code

import time
import urllib.response, requests

# from config.dev import CONTENT_IMAGE_UPLOAD
headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
# directory = CONTENT_IMAGE_UPLOAD + "en_" + time.strftime('%Y%m%d')
filename =  "sample.jpg"
try:
    resp = requests.get("https://www.miamiherald.com/latest-news/wfeh98/picture238148999/alternates/LANDSCAPE_1140/Screenshot%20(150).png", headers=headers).content
    with open(filename, "wb") as f:
        f.write(resp)
    print("image is saved")
except Exception as e:
    print(e)

This might help you :)

Changing User Agent in Python 3 for urrlib.request.urlopen

Marsilinou Zaky
  • 1,038
  • 7
  • 17