本文共 1026 字,大约阅读时间需要 3 分钟。
1、找到网页上图片的URL链接
找到网页上的图片右键即可 找到链接。如下例 2、设置保存的路径和文件名称>>> import requests>>> path="D://python_work//pics//1.jpg"
3、设置图片url链接
>>> url="http://5b0988e595225.cdn.sohucs.com/images/20180903/2de4877fe41e4dfe87a753c54c357dd9.jpeg"
4、用get请求捕获url
>>> r=requests.get(url)>>> r.status_code200
5、将捕获的图片(二进制)转化为JPG格式
>>> with open(path,'wb') as f:#将我们获取的文件打开并定义为文件标识符f f.write(r.content)#将返回的文件以二进制形式写回到文件中 51212>>> f.close()
效果如图:
6、用 爬虫爬取网页图片并存储通用代码框架形式:>>> import requests>>> import os>>> url="http://5b0988e595225.cdn.sohucs.com/images/20180903/2de4877fe41e4dfe87a753c54c357dd9.jpeg"#图片链接>>> root="D://python_work//pics"#根目录>>> path=root+url.split('/')[-1]#保存目录为根目录加上url链接以反斜杠分割的最后一个部分,也即path为本地路径中与图片最后名称一致的文件名称>>> try: if not os.path.exists(root):#如果根目录不存在就创建目录 os.mkdir(root) if not os.path.exists(path):#如果文件不存在,就利用代码获取网上的文件 r=requests.get(url) with open(path,'wb') as f: f.write(r.content) f.close() print("file save successfully") else: print("such file existed")except: print("failed") 51212file save successfully>>>
转载地址:http://vstmb.baihongyu.com/