爬虫实战_爬取静态单张图片

【Python网络爬虫与信息提取】.MOOC. 北京理工大学的这个视频教会了我爬取静态单张图片,我用的是Mac,所以里面的文件地址形式做了变更,代码如下:

import requests
import os
url = "https://pic.feizl.com/upload/allimg/170614/1JZ0G23-4.jpg"
root = "/Users/leo/Desktop/lianxi/"
path = root+url.split('/')[-1]
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("文件保存成功")
    else:
        print("文件已存在")
except:
    print("爬取失败")

显示爬取成功,桌面新建了lianxi文件夹,内存正确的图片。需要注意的是Mac下文件形式应该为/Users/leo/Desktop/lianxi/

猜你喜欢

转载自www.cnblogs.com/leogoforit/p/12540099.html