第一周单元3:Requests库网络爬虫实例下载图片-split
2021/8/8 6:08:40
本文主要是介绍第一周单元3:Requests库网络爬虫实例下载图片-split,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
获取用户输入的文件名
# coding:utf-8 import requests import os path = "D:\\pic\\{}.jpg".format(input("请输入文件名:")) url = "http://img.mp.itc.cn/upload/20160902/7cf52148ebbc4f378f5d55349bab6429_th.jpg" try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding with open(path, 'wb') as f: f.write(r.content) f.close() print("图片保存成功") except: print("Error")
判断目标目录是否存在,不存在则创建,并按原文件名保存
# coding:utf-8 import requests import os doc = "D:\\pic\\" url = "http://img.mp.itc.cn/upload/20160902/7cf52148ebbc4f378f5d55349bab6429_th.jpg" Path = doc + url.split("/")[-1] # 以“/”从最后一个字母向前分割url字符串 try: if not os.path.exists(doc): # 若不加这句,执行报错 os.mkdir(doc) # 若文件夹不存在,则创建 if not os.path.exists(Path): r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding with open(Path, 'wb') as f: f.write(r.content) f.close() print("图片保存成功") else: print("文件名已存在") except: print("Error")
这篇关于第一周单元3:Requests库网络爬虫实例下载图片-split的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求