Python Pycharm 爬虫 下载图片

刚刚学习了用Python编写一个爬虫程序,来从网站上获取图片,现在记录下来,防止以后忘记。

import requests
import re
import os

#这里调用了三个库,os是在保存文件到本地,修改、创建文件夹、文件的时候需要用到;re是正则表达的库文件;request是获取网站内容的库

#这次实验,我是在一个叫做Wallpaper的国外网站上获取图片,根据分析,这个网站上的每一个图片网址都符合一个规律:https://alpha.wallhaven.cc/wallpaper/跟上一个数字,然后有一个.jpg或者.png的后缀名。本次实验,我是下载了第4000到第4010张图片,下载完之后才发现全是妹子图,有点尴尬。。。

url = "https://alpha.wallhaven.cc/wallpaper/"
root = "G://photo//"

for i in range(4000,4010):
    try:
        r = requests.get(url+str(i))
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        ht = r.text
        a = re.search(r'<img id="wallpaper" src="',ht).end()
        b = re.search(r'(\.jpg)|(\.png)',ht[a:]).end()
        c = ht[a:a+b]
        if not os.path.exists(root):
            os.mkdir(root)
        path = root + c.split("/")[-1]
        if not os.path.exists(path):
            rr = requests.get("https:"+c)
            rr.raise_for_status()
            with open(path, "wb") as f:
                f.write(rr.content)
                # rr.content表示获取到的文件的二进制形式
                print("文件"+c.split("/")[-1]+"下载成功")
                f.close()
        else:
            print("文件已存在")
    except:
        print("fail")
        continue
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值