Crawlspider

一:Crawlspider简介

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

二:CrawlSpider整体的爬取流程:

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

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

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

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

三: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, Rulefrom 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响应回来的页面中,提取指定的urlRule(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 idivs=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.htmlimport scrapyclass 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.htmlclass CrawlproPipeline(object):def __init__(self):self.fp = Nonedef 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 itemdef close_spider(self,spider):print('结束爬虫')self.fp.close()

设置代理:

middlewares.py中间件:

设置代理:ip地址可以通过以下几个链接查找

http://ip.seofangfa.com/

settings.py里面设置:

DOWNLOADER_MIDDLEWARES = {'crawlPro.middlewares.Mydaili': 543,  #Mydaili名字就是中间件里面的类名
}

middlewares.py中间件设置:

class Mydaili(object):def process_request(self,request,spider):request.meta['proxy'] = "http://119.28.195.93:8888"

scrapy使用代理报错keyerror: proxy_爬虫Scrapy框架-Crawlspider链接提取器与规则解析器...相关推荐

  1. 使用PIL的Image.fromarray报错KeyError: ((1, 1, 1), ‘|u1‘)

    使用PIL的Image.fromarray报错 错误:使用PIL的Image.fromarray报错KeyError: ((1, 1, 1), '|u1') 原因:Pillow的fromarray函数 ...

  2. Django models新增属性后 迁移报错 KeyError ,--fake解决

    models在数据库已有表数据,新增一个field属性, isdeleted = models.IntegerField(default=0, blank=True, null=True) 然后进行m ...

  3. python之字典dict:明明有key,但是却报错KeyError

    问题:字典从文件中读出,字典中key含中文,明明有key,但是却报错KeyError:key不存在 预期:取出对应key的value 解决:将key前加上u,对key进行unicode编码,比如小红- ...

  4. 报错 KeyError

    当报错KeyError 1 时,多半是你使用一个不存在的key时报的错 来个dome a = {1:"a",2:"b",3:"c"}prin ...

  5. 求指教:报错KeyError: “None of [Index([‘2022/1/1 0:00:00‘, ... ],\n dtype=‘object‘] are in the [index]“

    求指教:Python运行报错KeyError: "None of [Index(['2022/1/1 0:00:00', - '2022/1/8 23:59:45'],\n dtype='o ...

  6. Debian/Ubuntu 对gpg和apt-key使用代理--报错解决:gpg: keyserver receive failed: Connection timed out

    gpg和apt-key使不会直接读取终端中设置的代理,需要单独设置. 参考地址:bash - keyserver timed out when trying to add a GPG public k ...

  7. vue 设置代理报错;occurred while trying to proxy request xxx

    报错: [HPM] Error occurred while trying to proxy request /oauth/validate from localhost:8080 to localh ...

  8. npm报错,安装不上依赖,npm代理报错

    npm报错:npm ERR! code ECONNREFUSED npm ERR! errno ECONNREFUSED,npm ERR! npm ERR! If you are behind a p ...

  9. zabbix 代理报错

    在部署zabbix代理的时候,zabbix_proxy的日志报错如下: sending data to server failed: error:"negative response: &q ...

最新文章

  1. cdialog创建后马上隐藏_隐藏你的小秘密,这款神器就是玩的这么6!
  2. python corrwith_python – pandas.DataFrame corrwith()方法
  3. vuejs目录结构启动项目安装nodejs命令,api配置信息思维导图版
  4. 天池 在线编程 扫雷(BFS)
  5. matlab中计算不等式的解,matlab解不等式
  6. 成交量与股价关系的深度剖析 (一)
  7. 开源的“底线”在哪里?
  8. gyp安装,及breakpad上的使用方法
  9. 数据分析岗位求职经验分享
  10. 双系统还是虚拟机 linux系统时间,mac装双系统好还是虚拟机好_mac装虚拟机好还是双系统-系统城...
  11. 【坑】html5中使用context.lineWidth设置线的宽度是1,然而输出的宽度是2的原因
  12. 获取文件名,文件名后缀以及elementui多张图片回显
  13. hbase snappy 安装_【hbase-部署】配置snappy压缩
  14. 【数字图像处理】Canny边缘检测C语言实现
  15. 计算机建立第2用户,2016年计算机二级VF备考练习题及参考答案(5)
  16. Facebook加好友被禁止,请问什么时候被解禁
  17. 霍兰德人格分析雷达图
  18. 使用Dreamweaver制作网页的20个技巧。
  19. 动力节点Maven课程笔记
  20. 使用OZMTool制作 ozmosis BIOS

热门文章

  1. Linux视频 pad,Wine 1.9.10 发布下载, 改善视频输出
  2. uboot源码——mmc驱动分析
  3. Android Studio 下使用git -- 个人,本地版本控制
  4. 处理字符集中的算式问题
  5. bzoj 1295: [SCOI2009]最长距离
  6. Example3_1
  7. 解决eclipse无法解析导入org.eclipse.swt库
  8. unlink(file_name)
  9. 字符串2在字符串1中第一次出现的位置strstr()
  10. 如何快速构建嵌入式全栈知识体系?