Кажется, что этому хосту, на котором вы получаете изображения, не нравятся заголовки по умолчанию, поставляемые с urllib.
Эта скорректированная версия, по-видимому, корректно извлекает ваши изображения:
import urllib.request
from urllib.error import URLError # the docs say this is the base error you need to catch
import time
import datetime,time
from PIL import Image
start_time = time.time()
today=time.strftime("%Y%m%d")
m=today=time.strftime("%m")
d=today=time.strftime("%d")
Y=today=time.strftime("%Y")
A=today=time.strftime("%b")
fetched_images = []
for i in range(1,5):
issue_id1=str(i)
url = "http://epaperlokmat.in/eNewspaper/News/LOK/MULK/"+str(Y) +"/"+str(m)+"/"+str(d)+"/"+str(Y+m+d)+"_"+str(i)+".jpeg"
try:
# First build the request, and adjust the headers to something else.
req = urllib.request.Request(url,
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
)
# Secondly fetch your image
s = urllib.request.urlopen(req)
contents = s.read()
# Append to your image-list
fetched_images.append(url)
except URLError:
print(url)
print('an error occurred while fetching: "{}"'.format(url))
continue
file = open("D:/IMAGES/"+issue_id1+".jpeg", "wb")
file.write(contents)
Чтобы уточнить, сначала создайте запрос с настроенными заголовками. Только после этого откройте URL-адрес, выбрав req
.
. Еще один способ go - использовать запросы. В вашем случае это на самом деле работает из коробки. Перед запуском вам нужно будет получить пакет запросов. pip install requests
import requests
import datetime,time
start_time = time.time()
today=time.strftime("%Y%m%d")
month=today=time.strftime("%m")
day=today=time.strftime("%d")
year=today=time.strftime("%Y")
url = "http://epaperlokmat.in/eNewspaper/News/LOK/MULK/{year}/{month}/{day}/{year}{month}{day}_{issue_id}.jpeg"
path = "D:/IMAGES/{issue_id}.jpeg"
fetched_images = []
for issue_id in range(1, 5):
try:
# Let's create the url for the given issue.
issue_url = url.format(
year=year,
month=month,
day=day,
issue_id=issue_id)
# GET the url content
req = requests.get(issue_url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}))
# Add the image to your list
fetched_images.append(issue_url)
# Save to file if succesful and close the file when done.
with open(path.format(issue_id=issue_id), 'wb') as f:
f.write(req.content)
except Exception as e:
# If something went wrong, just print the url and the error.
print('Failed to fetch {url} with error {e}'.format(
url=issue_url, e=e))