python 使用 urllib.urlretrieve()下载网络图片,在本地打开提示文件损坏无法打开

本文介绍了一种解决从特定网址下载图片时出现的问题的方法。通过使用带有自定义头部信息的urllib2请求替代直接的urlretrieve调用,可以成功下载并保存图片到指定路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

url = ‘http://www.xiaohuar.com/d/file/20170318/a5e3460073df58ed208ae3ec2ff46d07.jpg’

path_name ='xx'

urllib.urlretrieve(url, 'D:\imgs\%s.jpg' % path_name)

错误:

在本地打开图片


解决办法:

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) \
    AppleWebKit/537.36 (KHTML, like Gecko) \
        Chrome/35.0.1916.114 Safari/537.36',
    'Cookie': 'AspxAutoDetectCookieSupport=1'
}
request = urllib2.Request(url, None, header)
response = urllib2.urlopen(request)
with open("D:\zdq\imgs\%s.jpg" % path_name, "wb") as f:
    f.write(response.read())


import os import sys import urllib.request import zipfile import h5py # 目标文件路径 TARGET_FILE = r"D:\cs231n.github.io-master\assignments\2021\assignment3_colab\assignment3\cs231n\datasets\coco_captioning\coco2014_captions.h5" def handle_long_paths(path): """处理Windows长路径问题""" if len(path) > 260 and sys.platform == "win32": # 确保路径格式正确 if not path.startswith(r"\\?\\"): return r"\\?\\" + os.path.abspath(path) return path def fix_path_issues(file_path): """修复路径相关的问题""" # 处理长路径 file_path = handle_long_paths(file_path) # 创建缺失目录结构 os.makedirs(os.path.dirname(file_path), exist_ok=True) # 检查文件是否存在 if os.path.exists(file_path): print(f"✅ 文件已存在: {file_path}") return True, file_path print(f"❌ 文件不存在: {file_path}") return False, file_path def download_coco_dataset(file_path): """下载并解压COCO数据集""" dataset_url = "http://cs231n.stanford.edu/coco_captioning.zip" zip_path = os.path.join(os.path.dirname(file_path), "coco_captioning.zip") print(f"正在下载数据集: {dataset_url}") try: urllib.request.urlretrieve(dataset_url, zip_path) except Exception as e: print(f"下载失败: {str(e)}") return False, file_path print(f"解压文件到: {os.path.dirname(file_path)}") try: with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(os.path.dirname(file_path)) os.remove(zip_path) # 清理压缩包 except Exception as e: print(f"解压失败: {str(e)}") return False, file_path return os.path.exists(file_path), file_path def validate_hdf5_file(file_path): """验证HDF5文件完整性""" try: with h5py.File(file_path, 'r') as f: print("✅ 文件验证成功! 包含数据集:") print(list(f.keys())) # 输出数据集结构 return True except Exception as e: print(f"❌ 文件验证失败: {str(e)}") return False # 主执行流程 if __name__ == "__main__": # 处理路径问题 exists, current_path = fix_path_issues(TARGET_FILE) if not exists: # 下载数据集 downloaded, current_path = download_coco_dataset(current_path) if downloaded: print(f"✅ 数据集成功部署: {current_path}") else: print("❌ 数据集部署失败,请手动下载") sys.exit(1) # 验证文件 if not validate_hdf5_file(current_path): print("❌ 文件验证失败,数据集可能损坏") sys.exit(1) print("✨ 所有操作成功完成!") ❌ 文件不存在: D:\cs231n.github.io-master\assignments\2021\assignment3_colab\assignment3\cs231n\datasets\coco_captioning\coco2014_captions.h5 正在下载数据集: http://cs231n.stanford.edu/coco_captioning.zip 下载太慢是什么情况
最新发布
07-28
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值