首先简单分析可知,page后面为当前页码。
图片url的属性为 "data-src"
<img data-src="https://www.gifjia.com/wp-content/uploads/2019/10/15715434672091492-220x150.jpg" alt="甜到你心头白嫩美肤小姐姐板医生 用饱满山峰诠释萌系姐姐们!-GIF发源地" src="https://www.gifjia.com/wp-content/uploads/2019/10/15715434672091492-220x150.jpg" class="thumb" style="display: inline;">
import requests
from bs4 import BeautifulSoup
import os
# 爬取图片
def get_imgs(url,i):
print("正在爬取第"+str(i)+"页数据......")
res = requests.get(url)
res.encoding = res.apparent_encoding
# 把当前html数据保存至data变量
data = res.text
# 下面使用BeautifulSoup开始“熬汤”
soup = BeautifulSoup(data, "html.parser")
for src in soup.find_all("img"):
# 获得当前图片路径
img_url = src.get("data-src")
# 当前数据不为None,操作才有意义
if img_url != None:
# 文件夹路径
root = "d://images//"
# 拼接当前图片路径
img_path = root + img_url.split("/")[-1]
#判断当前文件夹是否存在,不存在就创建
if not os.path.exists(root):
os.mkdir(root)
# 判断当前图片是否存在,不存在就下载
if not os.path.exists(img_path):
# 使用request获取图片对象
img = requests.get(img_url)
with open(img_path, "wb") as f:
f.write(img.content)
print("第" + str(i) + "页爬取完成......")
# 获取前10页图片
for i in range(1,11):
# 爬取图片的网站
url="https://www.gifjia.com/category/meinv/page/"+str(i)+""
get_imgs(url,i)
print("爬取结束")
实验成果如下,代码虽然很low,但是,作为初学者对于学习爬虫又增加了一点点乐趣。