网络爬虫前奏之图片的爬取006

import requests
import os
#爬取图片的url
url = "https://images-cn.ssl-images-amazon.com/images/I/81M5fmmHKbL._AC_SL1500_.jpg"
#图片存放的目录
root="E://移动后的桌面//爬虫//image//"
#图片存放的目录加网页图片的名字
path=root+url.split('/')[-1]
try:
    #判断root目录是不是存在,不存在就创建
    if not os.path.exists(root):
        os.mkdir(root)
    #如果图片不存在,执行一段代码
    if not os.path.exists(path):
        #请求
        r=requests.get(url)
        #(wb):以二进制的形式打开文件只用于写入
        with open(path,'wb') as f:
            把图片的二进制保存
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已经存在")
except:
    print("爬取失败")
发布了50 篇原创文章 · 获赞 8 · 访问量 2103

猜你喜欢

转载自blog.csdn.net/qq_42753878/article/details/105609907