# -*- coding: utf-8 -*-
"""
@Time : 2022/3/19 16:31
@Author : Andrew
@File : 抓取优美图库.py
"""
# 1.拿到主页面的地址,获取主页面的源代码
# 2.通过f12进行定位,在该区域寻找图片,看是否需要进入子页面提取
# 3.检查发现,在本页面已经发现了图片的src,但是需要与https:拼接
# 4.下载图片 将没用的数据文件夹设为exclusion,这样下载的时候就不会太卡(因为pycharm会设置索引)
import re
import time
from bs4 import BeautifulSoup
import requests
# imgs = []
for i in range(1, 3, 1):
domain = "https://www.bizhizu.cn/"
url = "https://www.bizhizu.cn/wallpaper/" + str(i) + ".html"
resp = requests.get(url)
resp.encoding = "utf-8"
content = resp.text
page = BeautifulSoup(resp.text, "html.parser")
div = page.find("div", attrs={"class": "imgcont"})
lis = div.find_all("li")
for li in lis:
a = li.find_all("a")[1:]
href = a[0].get("href")
imageName = a[0].text
# 获取第二个子页面,并转bs4
contentChild1 = requests.get(href)
page2 = BeautifulSoup(contentChild1.text, "html.parser")
# page里面找class为text_con的p标签
p = page2.find("p", attrs={"class": "text_con"})
# p里面找class为xuButton的a标签
a = p.find("a", attrs={"class": "xuButton"})
# 获取a的href,并进行拼接
href_2 = a.get("href")
urlChild3 = domain+href_2
# 获取第三个子页面源代码
contentChild3 = requests.get(urlChild3)
page3 = BeautifulSoup(contentChild3.text, "html.parser")
a_showImage = page3.find("a", attrs={"class": "menu s4", "id": "download_yt"})
href3 = a_showImage.get("href")
imgIsDownload = requests.get(href3)
end = href3.split("/")[-1].split(".")[-1]
# 图片内容写入文件
with open("./壁纸族/"+imageName+"."+end, mode="wb") as f:
f.write(imgIsDownload.content)
time.sleep(1)
print(href3, 'over!!')
resp.close()
#这里就是要看得懂网页结构,网页设计的有时候高清图片的下载链接在当前页面的某个子链接里,需要不断地requests.get获取源代码,再bs4的find或者find_all进行唯一性标签定位,可能会重复多次,但套路一样