Python38 网络爬虫简介以及相关实例(爬虫获取青春有你2参赛选手照片)

一、网络爬虫准备工作

爬虫实践

普通用户上网过程:打开浏览器-->往目标站点发送请求-->接受响应数据-->渲染到页面上
爬虫程序:模拟浏览器-->往目标站点发送请求-->接受响应数据-->提取有用的数据-->保存到本地

爬虫的过程
1、发送请求(requests模块)
2、获取响应数据(服务器返回)
3、解析并提取数据(BeatufulSoup查找或者re正则)
4、保存数据

pip install beautifulsoup4 -t /home/library
request模块:requests是python实现的简单易用的HTTP库
官网地址:http://cn.python-requests.org/zh_CN/latest/
BeautifulSoup库:Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库。
网址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

二、爬虫实例(获取青春有你2参赛选手的相关照片)

# 作者:Kerwin Wan
# 开发时间:2022/8/22 1:06
"""
爬虫 青春有你
"""
import json
import os
import re
import requests
import datetime
# 获取当前时间
from bs4 import BeautifulSoup

today=datetime.date.today().strftime('%Y%m%d')
def crawl_player_data():
    # 爬取百度百科中青春有你2中参赛选手的信息 返回html
    headers={
        'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
    }
    url='https://baike.baidu.com/item/青春有你第二季'
    try:
        # url是请求的网页地址  headers是请求的模拟方式
        response=requests.get(url,headers=headers)
        # 将一段文档传入BeautifulSoup的构造方法,就可以得到一个文档的对象,可以传入一段字符串
        soup=BeautifulSoup(response.text,'lxml')

        # 返回的是class为table-view log-set-param的<table>所有标签
        tables=soup.find_all('table')
        crawl_table_title='参赛学员'
        for table in tables:
            # 寻找对应标签前面的一个同级div标签,寻找该标签下的h3标签
            table_title=table.find_previous_sibling("div").find_all("h3")
            for title in table_title:
                if crawl_table_title in title:
                    return table
    except Exception as e:
        print(e)
def parse_player_data(table_html):
    """
    从百度百科返回的html中解析得到选手信息,以当前日期作为文件名,存JSON文件,保存到Day2data目录下
    """
    bs = BeautifulSoup(str(table_html), 'lxml')
    # 找到表格的所有行
    all_trs = bs.find_all('tr')

    # 用来处理字串里面的单引号和双引号
    error_list = ['\'', '\"']

    # 定义一个list,存放选手
    stars = []

    # 我们从第二行开始,第一行为表头,我们不需要
    for tr in all_trs[1:]:
        all_tds = tr.find_all('td')
        print(all_tds)
        # 定义一个字典,存放选手信息
        star = dict()
        # 姓名, 因为姓名里面有"\n"字串,所以需要处理掉
        star["name"] = all_tds[0].text.replace("\n", "")
        # 个人百度百科链接
        star["link"] = 'https://baike.baidu.com' + all_tds[0].find('a').get('href')
        # 籍贯
        star["zone"] = all_tds[1].text
        # 星座
        star["constellation"] = all_tds[2].text

        # 花语,去除掉花语中的单引号或双引号
        flower_word = all_tds[3].text
        for c in flower_word:
            if c in error_list:
                flower_word = flower_word.replace(c, '')
        star["flower_word"] = flower_word

        # 公司, 公司的构成不一致,有超链接的会用到a标签,没有超链接的没有a标签,所以要做一下区分
        if not all_tds[4].find('a') is None:
            star["company"] = all_tds[4].find('a').text
        else:
            star["company"] = all_tds[4].text

        # 把学员信息dict插入到学员列表中
        stars.append(star)

    # 保存数据到JSON文件
    json_data = json.loads(str(stars).replace("\'", "\""))
    with open(today + '.json', 'w', encoding='UTF-8') as f:
        json.dump(json_data, f, ensure_ascii=False)



def crawl_player_pics():
    """
    爬取每个选手的百度百科图片,并保存
    """
    with open(today + '.json', 'r', encoding='UTF-8') as fr:
        json_array = json.loads(fr.read())

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'
    }

    for star in json_array:

        name = star['name']
        link = star['link']

        # 在以下完成对每个选手图片的爬取,将所有图片url存储在一个列表pic_urls中!
        response = requests.get(link, headers=headers)
        # print(response.text)
        # 将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串
        soup = BeautifulSoup(response.text, 'lxml')

        # 返回的是class为summary-pic的第一个<div>标签,这个里面有选手相册的地址
        # 这里用find去找,而不是find_all,因为有个选手的页面没有任何信息,如果用find_all()[0]的话,会报错。
        divs = soup.find('div', {'class': 'summary-pic'})

        pic_urls = []

        if divs:
            # 对当前节点标签a进行查找
            img_srcs = divs.find_all('a')[0]
            # print(img_srcs)
            # 这里我们找到相册的网址在去抓图片就可以抓到全部图片,如果我们只获取src的地址,就只能抓到一张照片
            img_addr = img_srcs.get("href")
            # print(img_addr)
            response = requests.get('https://baike.baidu.com' + img_addr, headers=headers)
            soup = BeautifulSoup(response.text, 'lxml')

            # 返回的是class为pic-item的<a>所有标签,这个a标签里面就是所有照片的网址。
            all_a = soup.find_all('a', {'class': 'pic-item'})
            for a in all_a:
                img_lists = a.find_all('img')
                for img in img_lists:
                    img_addr = img.get("src")
                    # img_addr = img.get("data-sign")
                    # 这里我们把网址/resize后面的不要了,不然爬下来的是缩略图而不是大图。
                    img_addr = img_addr.split("/resize")[0]
                    # print(img_addr)
                    if img_addr:
                        pic_urls.append(img_addr)

        # 根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中!
        down_pic(name, pic_urls)


def down_pic(name, pic_urls):
    """
    根据图片链接列表pic_urls, 下载所有图片,保存在以name命名的文件夹中,
    """
    path = './pics/' + name + '/'

    if not os.path.exists(path):
        os.makedirs(path)

    for i, pic_url in enumerate(pic_urls):
        try:
            pic = requests.get(pic_url, timeout=15)
            string = str(i + 1) + '.jpg'
            with open(path + string, 'wb') as f:
                f.write(pic.content)
                print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
        except Exception as e:
            print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
            print(e)
            continue

def show_pic_path(path):
    """
    遍历所爬取的每张图片,并打印所有图片的绝对路径
    """
    pic_num = 0
    for (dirpath, dirnames, filenames) in os.walk(path):
        for filename in filenames:
            pic_num += 1
            name=os.path.join(dirpath, filename).replace('\\','/')
            print("第%d张照片:%s" % (pic_num, name))
    print("共爬取《青春有你2》选手的%d照片" % pic_num)
if __name__ == '__main__':

    # 获取当天的日期,并进行格式化,用于后面文件命名,格式:20200420
    today = datetime.date.today().strftime('%Y%m%d')
    # print(today)

    # 爬取百度百科中《青春有你2》中参赛选手信息,返回html
    html = crawl_player_data()

    # 解析html,得到选手信息,保存为json文件
    parse_player_data(html)

    # 从每个选手的百度百科页面上爬取图片,并保存
    crawl_player_pics()

    # 打印所爬取的选手图片路径
    show_pic_path('./pics/')

    print("所有信息爬取完成!")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值