这两天在学算法,昨天感觉力扣的头像不好看,刚好有两天没碰爬虫了,就百度了下头像网,顺便 练练手,再换个头像
目标:https://www.gx8899.com/katong/
思路实现
- 分页 1-n页
- 每一页有16张封面,每张封面点进去有这个封面的全部系列图片
- 最小单位:一个封面的全部系列图片
一级页面
- 获取第一页源码并提取每个封面的页面链接
resp=requests.get(url=url,headers=headers)
resp.encoding='gb2312'
exSoup=BeautifulSoup(resp.text,'html.parser')
one_hrefs=exSoup.select('a[target="_blank"]')
#获取封面链接
img_href=re.findall(r'<a href="(.*?).html"',str(one_hrefs))
二级页面
- 获取图片名称和图片的url
count=0
for i in img_href:
count+=1
#封面的链接
imgs_link='https://www.gx8899.com'+str(i)+'.html'
imgs=requests.get(imgs_link,headers)
imgs.encoding='gb2312'
soup=BeautifulSoup(imgs.text,'html.parser')
title=soup.select('title')
#封面名称
name=re.findall(r'<title>(.*?) - 个性8899头像网</title>',str(title))
img=soup.select('img[alt=""]')
#图片url
imgresult=re.findall(r'src="(.*?)"',str(img))
try-except 保存
- 防止因某一页或者某一张图片名称或者url问题导致整个程序中止
for j in range(len(imgresult)):
saveimg=requests.get(imgresult[j],headers)
try:
with open(f'D:/爬取图片/8899头像网/{name[0]}{j}.jpg','wb') as f:
f.write(saveimg.content)
#简单反爬
time.sleep(0.5)
print(f'{name[0]}{j}.jpg下载完毕!')
except:
print('下载失败!')
完整程序
代码
由于第一页在一边写一边运行测试的时候已经爬下来了,所以代码是从第二页开始的
'''
2021-8-6
爬取个性8899头像网
https://www.gx8899.com/katong/
'''
import random,time
import re
import requests
from bs4 import BeautifulSoup
import ualist
for n in range(2,16):
print(f'正在下载 卡通头像 第{n}页-------------------------------------------------------------')
url=f'https://www.gx8899.com/katong/index_{n}.html'
headers = {
"user-agent": random.choice(ualist.Ualist)
}
resp=requests.get(url=url,headers=headers)
resp.encoding='gb2312'
exSoup=BeautifulSoup(resp.text,'html.parser')
one_hrefs=exSoup.select('a[target="_blank"]')
img_href=re.findall(r'<a href="(.*?).html"',str(one_hrefs))
count=0
for i in img_href:
count+=1
imgs_link='https://www.gx8899.com'+str(i)+'.html'
imgs=requests.get(imgs_link,headers)
imgs.encoding='gb2312'
soup=BeautifulSoup(imgs.text,'html.parser')
title=soup.select('title')
name=re.findall(r'<title>(.*?) - 个性8899头像网</title>',str(title))
img=soup.select('img[alt=""]')
imgresult=re.findall(r'src="(.*?)"',str(img))
print("\033[0;31m%s\033[0m" % f'{count}---正在打印---{name[0]}--信息---{imgs_link}')
for j in range(len(imgresult)):
saveimg=requests.get(imgresult[j],headers)
try:
with open(f'D:/爬取图片/8899头像网/{name[0]}{j}.jpg','wb') as f:
f.write(saveimg.content)
time.sleep(0.5)
print(f'{name[0]}{j}.jpg下载完毕!')
except:
print('下载失败!')
imgs.close()
resp.close()
ualist
上面调用的这个ualist是我在网上找了上百个user-agent,然后用写了个剔除重复内容的代码,把剩下的保存到ualist.py
import ualist
headers = {
"user-agent": random.choice(ualist.Ualist)
}
- 由于ualist太长了,就不放出来了,感兴趣的话可以看一下我前面的几篇爬虫的u-a
2021-08-01 Python-爬虫练手:爬取上千张“萌妹子“网美图
2021-07-31 Python爬虫练手项目–爬取上千张明星美图
2021-07-28 Python爬虫之爬取某虫网美女图片实战 - 或者就用自己浏览器的u-a
随便点一个网页按F12—>Network—>Headers:复制自己的user-agent
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 "
}
记得关闭请求
imgs.close()
resp.close()
成品欣赏
for n in range(2,16):
算上第一页的一共爬了15页,到后面两三页有保存失败的一共爬下来了1700+