爬虫Scrapy框架-Crawlspider链接提取器与规则解析器

一:Crawlspider简介

    CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。

二:Crawlspider使用

实例:爬取https://www.qiushibaike.com/主页帖子作者以及内容

1.创建scrapy工程

2.创建爬虫文件

注意:对比以前的指令多了 "-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。

3.生成的目录结构如下:

CrawlDemo.py爬虫文件设置:

  LinkExtractor:顾名思义,链接提取器。
  Rule : 规则解析器。根据链接提取器中提取到的链接,根据指定规则提取解析器链接网页中的内容。

  Rule参数介绍:

    参数1:指定链接提取器

    参数2:指定规则解析器解析数据的规则(回调函数)

    参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中,当callback为None,参数3的默认值为true。

  rules=( ):指定不同规则解析器。一个Rule对象表示一种提取规则。

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

from crawlPro.items import CrawlproItem
class CrawldemoSpider(CrawlSpider):
    name = ‘crawlDemo‘
    # allowed_domains = [‘www.qiushibaike.com‘]
    start_urls = [‘http://www.qiushibaike.com/‘]
    #rules元祖中存放的是不同规则解析器(封装好了某种解析规则)
    rules = (
        # Rule: 规则解析器,可以将连接提取器提取到的所有连接表示的页面进行指定规则(有中间的回调函数决定)的解析
        #LinkBxtractor:连接提取器,会去上面起始url响应回来的页面中,提取指定的url
        Rule(LinkExtractor(allow=r‘/8hr/page/\d+‘), callback=‘parse_item‘, follow=True), #follow=True可以跟进保证将所有页面都提取出来(实际就是去重功能)
    )

    def parse_item(self, response):
        # i = {}
        # #i[‘domain_id‘] = response.xpath(‘//input[@id="sid"]/@value‘).extract()
        # #i[‘name‘] = response.xpath(‘//div[@id="name"]‘).extract()
        # #i[‘description‘] = response.xpath(‘//div[@id="description"]‘).extract()
        # return i
        divs=response.xpath(‘//div[@id="content-left"]/div‘)
        for div in divs:
            item=CrawlproItem()
            #提取糗百中段子的作者
            item[‘author‘] = div.xpath(‘./div[@class="author clearfix"]/a[2]/h2/text()‘).extract_first().strip(‘\n‘)
            # 提取糗百中段子的内容
            item[‘content‘] = div.xpath(‘.//div[@class="content"]/span/text()‘).extract_first().strip(‘\n‘)

            yield item  #将item提交到管道

item.py文件设置:

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class CrawlproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author=scrapy.Field()
    content=scrapy.Field()

pipelines.py管道文件设置:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don‘t forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

class CrawlproPipeline(object):
    def __init__(self):
        self.fp = None

    def open_spider(self,spider):
        print(‘开始爬虫‘)
        self.fp = open(‘./data.txt‘,‘w‘,encoding=‘utf-8‘)

    def process_item(self, item, spider):
        # 将爬虫文件提交的item写入文件进行持久化存储
        self.fp.write(item[‘author‘]+‘:‘+item[‘content‘]+‘\n‘)
        return item

    def close_spider(self,spider):
        print(‘结束爬虫‘)
        self.fp.close()

原文地址:https://www.cnblogs.com/yangzhizong/p/9741196.html

时间: 2024-08-01 04:01:24

爬虫Scrapy框架-Crawlspider链接提取器与规则解析器的相关文章

Scrapy框架——CrawlSpider爬取某热线网站

CrawlSpider Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页, 而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合. 创建项目指令: scrapy startproject sumPro CrawlSpider创建: scrapy genspider -t crawl sun "http:/

python爬虫--scrapy框架

Scrapy 一 介绍 Scrapy简介 1.Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛 2.框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片,非常之方便 Scrapy架构图 Scrapy主要包括了以下组件: 1.引擎(Scrapy) 用来处理整个系统的数据流处理, 触发事务(框架核心) 2.调度器(Scheduler) 用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可

python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)

操作环境:python3 在上一文中python爬虫scrapy框架--人工识别登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前的文章便于理解 本文将介绍如何用scrapy来登录知乎. 不多说,直接上代码: import scrapy import re import json class ZhihuSpider(scrapy.Spider): name = 'zhihu' allowed_domains = ['www.zhi

安装爬虫 scrapy 框架前提条件

安装爬虫 scrapy 框架前提条件 (不然 会 报错) 1 pip install pypiwin32 原文地址:https://www.cnblogs.com/xmdykf/p/11374484.html

python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。

本次python爬虫百步百科,里面详细分析了爬虫的步骤,对每一步代码都有详细的注释说明,可通过本案例掌握python爬虫的特点: 1.爬虫调度入口(crawler_main.py) # coding:utf-8from com.wenhy.crawler_baidu_baike import url_manager, html_downloader, html_parser, html_outputer print "爬虫百度百科调度入口" # 创建爬虫类class SpiderMai

springmvc 前端控制器,映射器,适配器,视图解析器

1.前端控制器DispatcherServlet的配置,在web.xml进行配置即可跟servlet的配置方式相同 1)contextConfigLocation配置sprimgmvc加载的配置文件(配置处理器映射器,适配器等等)如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml) 2) 第一种:*.action,访问以.action结尾 由DispatcherServlet进

Scrapy框架CrawlSpider类爬虫实例

CrawlSpider类爬虫中: rules用于定义提取URl地址规则,元祖数据有顺序 #LinkExtractor 连接提取器,提取url地址  #callback 提取出来的url地址的response会交给callback处理 #follow 当前url地址的响应是否重新经过rules进行提取url地址 cf.py具体实现代码如下(简化版): 1 # -*- coding: utf-8 -*- 2 import scrapy 3 from scrapy.linkextractors imp

爬虫----Scrapy框架

一.介绍 Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速.简单.可扩展的方式从网站中提取所需的数据.但目前Scrapy的用途十分广泛,可用于如数据挖掘.监测和自动化测试等领域,也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫. Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架.因此Scrapy使用了一

数据之路 - Python爬虫 - Scrapy框架

一.Scrapy框架入门 1.Scrapy框架介绍 Scrapy是一个基于Twisted的异步处理框架,是纯Python实现的爬虫框架,其架构清晰,榄块之间的榈合程度低,可扩展性极强,可以灵活完成各种需求. Engine:引擎,处理整个系统的数据流处理.触发事务,是整个框架的核心. Item:项目,它定义了爬取结果的数据结构,爬取的数据会被赋值成该Item对象. Scheduler:调度器,接受引擎发过来的请求并将其加入队列中, 在引擎再次请求的时候将请求提供给引擎. Downloader:下载