1. 前言

家喻户晓,Python 最风行的爬虫框架是 Scrapy,它次要用于爬取网站结构性数据

明天举荐一款更加简略、轻量级,且功能强大的爬虫框架:feapder

2. 介绍及装置
和 Scrapy 相似,feapder 反对轻量级爬虫、分布式爬虫、批次爬虫、爬虫报警机制等性能

内置的 3 种爬虫如下:

  • AirSpider

轻量级爬虫,适宜简略场景、数据量少的爬虫

  • Spider

分布式爬虫,基于 Redis,实用于海量数据,并且反对断点续爬、主动数据入库等性能

  • BatchSpider

分布式批次爬虫,次要用于须要周期性采集的爬虫

在实战之前,咱们在虚拟环境下装置对应的依赖库

# 装置依赖库pip3 install feapder

3. 实战一下
咱们以最简略的 AirSpider 来爬取一些简略的数据

指标网站:aHR0cHM6Ly90b3BodWIudG9kYXkvIA==

具体实现步骤如下( 5 步)

3-1 创立爬虫我的项目

首先,咱们应用「 feapder create -p 」命令创立一个爬虫我的项目

# 创立一个爬虫我的项目feapder create -p tophub_demo

3-2 创立爬虫 AirSpider

命令行进入到 spiders 文件夹目录下,应用「 feapder create -s 」命令创立一个爬虫

cd spiders# 创立一个轻量级爬虫feapder create -s tophub_spider 1

其中

  • 1 为默认,示意创立一个轻量级爬虫 AirSpider
  • 2 代表创立一个分布式爬虫 Spider
  • 3 代表创立一个分布式批次爬虫 BatchSpider

3-3 配置数据库、创立数据表、创立映射 Item

以 Mysql 为例,首先咱们在数据库中创立一张数据表

# 创立一张数据表create table topic(    id         int auto_increment        primary key,    title      varchar(100)  null comment '文章题目',    auth       varchar(20)   null comment '作者',    like_count     int default 0 null comment '喜爱数',    collection int default 0 null comment '珍藏数',    comment    int default 0 null comment '评论数');

而后,关上我的项目根目录下的 settings.py 文件,配置数据库连贯信息

# settings.pyMYSQL_IP = "localhost"MYSQL_PORT = 3306MYSQL_DB = "xag"MYSQL_USER_NAME = "root"MYSQL_USER_PASS = "root"

最初,创立映射 Item( 可选 )

进入到 items 文件夹,应用「 feapder create -i 」命令创立一个文件映射到数据库

PS:因为 AirSpider 不反对数据主动入库,所以这步不是必须

3-4 编写爬虫及数据解析

第一步,首先使「 MysqlDB 」初始化数据库

from feapder.db.mysqldb import MysqlDBclass TophubSpider(feapder.AirSpider):    def __init__(self, *args, **kwargs):        super().__init__(*args, **kwargs)        self.db = MysqlDB()

第二步,在 start_requests 办法中,指定爬取主链接地址,应用关键字「download_midware 」配置随机 UA

import feapderfrom fake_useragent import UserAgentdef start_requests(self):    yield feapder.Request("https://tophub.today/", download_midware=self.download_midware)def download_midware(self, request):    # 随机UA    # 依赖:pip3 install fake_useragent    ua = UserAgent().random    request.headers = {'User-Agent': ua}    return request

第三步,爬取首页题目、链接地址

应用 feapder 内置办法 xpath 去解析数据即可

def parse(self, request, response):    # print(response.text)    card_elements = response.xpath('//div[@class="cc-cd"]')    # 过滤出对应的卡片元素【什么值得买】    buy_good_element = [card_element for card_element in card_elements if                        card_element.xpath('.//div[@class="cc-cd-is"]//span/text()').extract_first() == '什么值得买'][0]    # 获取外部文章题目及地址    a_elements = buy_good_element.xpath('.//div[@class="cc-cd-cb nano"]//a')    for a_element in a_elements:        # 题目和链接        title = a_element.xpath('.//span[@class="t"]/text()').extract_first()        href = a_element.xpath('.//@href').extract_first()        # 再次下发新工作,并带上文章题目        yield feapder.Request(href, download_midware=self.download_midware, callback=self.parser_detail_page,                              title=title)

第四步,爬取详情页面数据

上一步下发新的工作,通过关键字「 callback 」指定回调函数,最初在 parser_detail_page 中对详情页面进行数据解析

def parser_detail_page(self, request, response):    """    解析文章详情数据    :param request:    :param response:    :return:    """    title = request.title    url = request.url    # 解析文章详情页面,获取点赞、珍藏、评论数目及作者名称    author = response.xpath('//a[@class="author-title"]/text()').extract_first().strip()    print("作者:", author, '文章题目:', title, "地址:", url)    desc_elements = response.xpath('//span[@class="xilie"]/span')    print("desc数目:", len(desc_elements))    # 点赞    like_count = int(re.findall('\d+', desc_elements[1].xpath('./text()').extract_first())[0])    # 珍藏    collection_count = int(re.findall('\d+', desc_elements[2].xpath('./text()').extract_first())[0])    # 评论    comment_count = int(re.findall('\d+', desc_elements[3].xpath('./text()').extract_first())[0])    print("点赞:", like_count, "珍藏:", collection_count, "评论:", comment_count)

3-5 数据入库

应用下面实例化的数据库对象执行 SQL,将数据插入到数据库中即可

# 插入数据库sql = "INSERT INTO topic(title,auth,like_count,collection,comment) values('%s','%s','%s','%d','%d')" % (title, author, like_count, collection_count, comment_count)# 执行self.db.execute(sql)

4. 最初
最近整顿了几百 G 的 Python 学习材料,蕴含新手入门电子书、教程、源码等等,收费分享给大家!想要的返回 “Python 编程学习圈”,发送 “J” 即可收费取得