实例4:网络图片的爬取和存储
Posted tingtin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实例4:网络图片的爬取和存储相关的知识,希望对你有一定的参考价值。
网络图片链接的格式:http://www.example.com/picture.jpg
图片爬取代码
import requests import os #url = ‘https://image.baidu.com/search/detail?ct=503316480&z=&tn=baiduimagedetail&ipn=d&word=%E7%8B%97&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=-1&hd=&latest=©right=&cs=3454764333,132856788&os=2732860056,534267934&simid=3414273181,65897104&pn=22&rn=1&di=47850&ln=1781&fr=&fmq=1589705073726_R&ic=&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&is=0,0&istype=2&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=http%3A%2F%2Fwww.goumin.com%2Fattachments%2Fphoto%2F0%2F0%2F95%2F24365%2F6237648.jpg&rpstart=0&rpnum=0&adpicid=0&force=undefined‘ url = ‘http://img0.dili360.com/ga/M00/48/F7/wKgBy1llvmCAAQOVADC36j6n9bw622.tub.jpg‘ root = ‘E://dasande//dasi//Graduation practice//Reptile//material//‘ #E:dasandedasiGraduation practiceReptile是错的 path = root + url.split(‘/‘)[-1]#wKgBy1llvmCAAQOVADC36j6n9bw622.tub.jpg try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(url) print(r.status_code) r.encoding = r.apparent_encoding print(r.text) r.raise_for_status() with open(path, ‘wb‘) as f: # 以二进制写入的权限打开文件,图片是二进制格式 f.write(r.content) # 写入图片的二进制数据 f.close() # 关闭文件 print("文件保存成功") else: print(‘文件已存在‘) except: print(‘爬取失败‘)
以上是关于实例4:网络图片的爬取和存储的主要内容,如果未能解决你的问题,请参考以下文章