2021-08-07 Python-爬虫练手:爬取上千张动漫卡通头像


这两天在学算法,昨天感觉力扣的头像不好看,刚好有两天没碰爬虫了,就百度了下头像网,顺便 练练手,再换个头像

目标:https://www.gx8899.com/katong/
在这里插入图片描述

思路实现

  1. 分页 1-n页
  2. 每一页有16张封面,每张封面点进去有这个封面的全部系列图片
  3. 最小单位:一个封面的全部系列图片

一级页面

  • 获取第一页源码并提取每个封面的页面链接
    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)
    }

在这里插入图片描述

    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+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面是一个简单的 Python 爬虫教程,可以批量爬取指定网站的图片: 首先,我们需要安装 requests 和 BeautifulSoup 这两个库。可以通过以下命令进行安装: ``` pip install requests pip install beautifulsoup4 ``` 接下来,我们需要编写代码。以下是一个示例代码,可以爬取指定网站的图片并保存到本地: ```python import requests from bs4 import BeautifulSoup import os # 爬取图片的网站 url = "https://www.example.com/" # 请求头,模拟浏览器访问 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} # 发送请求,获取网页内容 response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # 创建保存图片的文件夹 if not os.path.exists("images"): os.makedirs("images") # 遍历所有的图片标签,获取图片链接并保存到本地 for img in soup.find_all("img"): img_url = img.get("src") if img_url.startswith("http"): response = requests.get(img_url) with open("images/" + os.path.basename(img_url), "wb") as file: file.write(response.content) print("已保存图片:", img_url) ``` 在上述代码中,我们首先定义了要爬取的网站的 URL。然后,我们使用 requests 库发送一个 GET 请求,获取网页的 HTML 内容。接着,我们使用 BeautifulSoup 库对 HTML 进行解析,获取所有的图片标签。最后,我们使用 requests 库再次发送 GET 请求,获取图片的二进制数据,并保存到本地的 images 文件夹中。 注意,这里我们使用了一个 if 判断来过滤掉非 HTTP 开头的图片链接,以避免出现下载错误的情况。 为了更好的用户体验,代码中还加入了一些注释,方便大家理解。 希望这个简单的 Python 爬虫教程能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值