Python网络爬虫之Scrapy框架(CrawlSpider)

提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法?

方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法)。

方法二:基于CrawlSpider的自动爬取进行实现(更加简洁和高效)。

CrawlSpider使用

1.创建scrapy工程:scrapy startproject projectName

2.创建爬虫文件:scrapy genspider -t crawl spiderName www.xxx.com

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

3.观察生成的爬虫文件

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class ChoutidemoSpider(CrawlSpider):
name = 'choutiDemo'
#allowed_domains = ['www.chouti.com']
start_urls = ['http://www.chouti.com/'] rules = (
Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', 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 - 2,3行:导入CrawlSpider相关模块    - 7行:表示该爬虫程序是基于CrawlSpider类的    - 12,13,14行:表示为提取Link规则    - 16行:解析方法

CrawlSpider类和Spider类的最大不同是CrawlSpider多了一个rules属性,其作用是定义”提取动作“。在rules中可以包含一个或多个Rule对象,在Rule对象中包含了LinkExtractor对象。

LinkExtractor:顾名思义,链接提取器。

    LinkExtractor(

         allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。

         deny=xxx,  # 满足正则表达式的则不会被提取。

         restrict_xpaths=xxx, # 满足xpath表达式的值会被提取

         restrict_css=xxx, # 满足css表达式的值会被提取

         deny_domains=xxx, # 不会被提取的链接的domains。 

    )
    - 作用:提取response中符合规则的链接。

    

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

     Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)

    - 参数介绍:

      参数1:指定链接提取器

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

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

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

CrawlSpider整体爬取流程:

    a)爬虫文件首先根据起始url,获取该url的网页内容

    b)链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取

    c)规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析

    d)将解析数据封装到item中,然后提交给管道进行持久化存储

爬取糗事百科糗图板块的所有页码数据

	# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class CrawldemoSpider(CrawlSpider):
name = 'qiubai'
#allowed_domains = ['www.qiushibaike.com']
start_urls = ['https://www.qiushibaike.com/pic/'] #连接提取器:会去起始url响应回来的页面中提取指定的url
link = LinkExtractor(allow=r'/pic/page/\d+\?') #s=为随机数
link1 = LinkExtractor(allow=r'/pic/$')#爬取第一页
#rules元组中存放的是不同的规则解析器(封装好了某种解析规则)
rules = (
#规则解析器:可以将连接提取器提取到的所有连接表示的页面进行指定规则(回调函数)的解析
Rule(link, callback='parse_item', follow=True),
Rule(link1, callback='parse_item', follow=True),
) def parse_item(self, response):
print(response)

爬虫文件

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qiubaiBycrawl.items import QiubaibycrawlItem
import re
class QiubaitestSpider(CrawlSpider):
name = 'qiubaiTest'
#起始url
start_urls = ['http://www.qiushibaike.com/'] #定义链接提取器,且指定其提取规则
page_link = LinkExtractor(allow=r'/8hr/page/\d+/') rules = (
#定义规则解析器,且指定解析规则通过callback回调函数
Rule(page_link, callback='parse_item', follow=True),
) #自定义规则解析器的解析规则函数
def parse_item(self, response):
div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list:
#定义item
item = QiubaibycrawlItem()
#根据xpath表达式提取糗百中段子的作者
item['author'] = div.xpath('./div/a[2]/h2/text()').extract_first().strip('\n')
#根据xpath表达式提取糗百中段子的内容
item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first().strip('\n') yield item #将item提交至管道

item文件

# -*- 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 QiubaibycrawlItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
author = scrapy.Field() #作者
content = scrapy.Field() #内容

管道文件:

# -*- 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 QiubaibycrawlPipeline(object): def __init__(self):
self.fp = None def open_spider(self,spider):
print('开始爬虫')
self.fp = open('./data.txt','w') 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()

Python网络爬虫之Scrapy框架(CrawlSpider)的更多相关文章

  1. 16.Python网络爬虫之Scrapy框架(CrawlSpider)

    引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法 ...

  2. 16,Python网络爬虫之Scrapy框架(CrawlSpider)

    今日概要 CrawlSpider简介 CrawlSpider使用 基于CrawlSpider爬虫文件的创建 链接提取器 规则解析器 引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话, ...

  3. 网络爬虫之scrapy框架(CrawlSpider)

    一.简介 CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能之外,还派生了其自己独有的更强大的特性和功能.其中最显著的功能就是"LinkExtractor ...

  4. Python逆向爬虫之scrapy框架,非常详细

    爬虫系列目录 目录 Python逆向爬虫之scrapy框架,非常详细 一.爬虫入门 1.1 定义需求 1.2 需求分析 1.2.1 下载某个页面上所有的图片 1.2.2 分页 1.2.3 进行下载图片 ...

  5. 网络爬虫值scrapy框架基础

    简介 Scrapy是一个高级的Python爬虫框架,它不仅包含了爬虫的特性,还可以方便的将爬虫数据保存到csv.json等文件中. 首先我们安装Scrapy. 其可以应用在数据挖掘,信息处理或存储历史 ...

  6. Python学习---爬虫学习[scrapy框架初识]

    Scrapy Scrapy是一个框架,可以帮助我们进行创建项目,运行项目,可以帮我们下载,解析网页,同时支持cookies和自定义其他功能. Scrapy是一个为了爬取网站数据,提取结构性数据而编写的 ...

  7. python爬虫之Scrapy框架(CrawlSpider)

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬去进行实现的(Request模块回调) 方法二:基于CrawlSpi ...

  8. python网络爬虫之scrapy 工程创建以及原理介绍

    执行scrapy startproject XXXX的命令,就会在对应的目录下生成工程 在pycharm中打开此工程目录:并在Run中选择Edit Configuration 点击+创建一个Pytho ...

  9. 网络爬虫之scrapy框架设置代理

    前戏 os.environ()简介 os.environ()可以获取到当前进程的环境变量,注意,是当前进程. 如果我们在一个程序中设置了环境变量,另一个程序是无法获取设置的那个变量的. 环境变量是以一 ...

随机推荐

  1. js字符转处理

    那几个函数的应用: <script> //全局变量删不掉,而全局属性能删掉 var a=123; function aa () { b=321; delete b; } aa(); del ...

  2. Oracle执行存储过程报错——ora-01031:权限不足

    执行DDL报错 在oracle存储过程中,默认是可以直接执行DML和DQL的,但是执行CREATE这种的DDL则需要借助EXECUTE IMMEDIATE 如: create or replace p ...

  3. expect安装测试-批量用户管理

    安装: yum list | grep expect yum install expect 批量创建用户: ansible mysqldb -m user -a 'name=ansible state ...

  4. ubuntu系统jdk安装及环境变量配置

    一.安装jdk 1.下载linux版本jdk,我用的是最新版本1.8.0_102 2.打开终端,进入jdk的存放路径 3.解压.tar.gz文件 sudo tar zxvf jdk-8u102-lin ...

  5. 2.EF的数据审计日志

    转载:采用EntityFramework.Extended 对EF进行扩展(Entity Framework 延伸系列2) 数据审计日志: 先说一下这个审计的概念,就是对所有的实体的操作(增,删,改) ...

  6. 自然常数 e 的理解与应用

    某彩票中奖率是百万分之一,则一个人买一百万张彩票仍不中奖的概率是: (1−1106)106≈1e e 往往出现在: 许多微小事件带来的总体变化 随机性和无穷多:

  7. Timer A UP mode 中断

    Timer_A, Toggle P1.0, CCR0 Up Mode ISR, DCO SMCLK //  Description: Toggle P1.0 using software and TA ...

  8. Git文件不显示图标/标识

    初次使用Git服务功能,做了很多探路事情,记录下刚刚遇到的问题 情况:安装了Git应用程序,或者也安装了TortoiseGit-1.8.16.0-64bit(类似SVN工具)后,上传下载文件没有问题, ...

  9. 根据JSON创建对应的HIVE表

    本文提供一种用SCALA把JSON串转换为HIVE表的方法,由于比较简单,只贴代码,不做解释.有问题可以留言探讨 package com.gabry.hiveimport org.json4s._im ...

  10. 微信小程序图片选择,预览和删除

    这里均用的是小程序原生api 废话不多说直接上栗子: <view class="addImv"> <!--这个是已经选好的图片--> <view wx ...