【发布时间】:2019-01-16 08:17:43
【问题描述】:
所以我正在构建一个 Python 脚本来从 url 列表中下载图像。该脚本在一定程度上可以工作。我不希望它下载网址不存在的图像。我处理了一些使用状态代码的图像,但仍然得到坏图像。 我仍然得到很多我不想要的图像。比如这些:
这是我的代码:
import os
import requests
import shutil
import random
import urllib.request
def sendRequest(url):
try:
page = requests.get(url, stream = True, timeout = 1)
except Exception:
print('error exception')
pass
else:
#HERE IS WHERE I DO THE STATUS CODE
print(page.status_code)
if (page.status_code == 200):
return page
return False
def downloadImage(imageUrl: str, filePath: str):
img = sendRequest(imageUrl)
if (img == False):
return False
with open(filePath, "wb") as f:
img.raw.decode_content = True
try:
shutil.copyfileobj(img.raw, f)
except Exception:
return False
return True
os.chdir('/Users/nikolasioannou/Desktop')
os.mkdir('folder')
fileURL = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n04122825'
data = urllib.request.urlopen(fileURL)
output_directory = '/Users/nikolasioannou/Desktop/folder'
line_count = 0
for line in data:
img_name = str(random.randrange(0, 10000)) + '.jpg'
image_path = os.path.join(output_directory, img_name)
downloadImage(line.decode('utf-8'), image_path)
line_count = line_count + 1
#print(line_count)
感谢您的宝贵时间。任何想法都表示赞赏。
真诚地, 尼古拉斯
【问题讨论】:
-
您可以检查 jpeg 或 png 标头和魔术序列
-
感谢您的快速回复!抱歉,我对 Python 还很陌生,我该怎么做? @juliusmh
-
问题是你得到的不是像 HTML 页面那样的图像,还是你得到无用的占位符图像?
标签: python exception error-handling httprequest urlrequest