刚刚学习了用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