CrawlSpider

Scrapy框架中分两类爬虫,Spider类和CrawlSpider类。

它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,

而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。

创建项目指令:

scrapy startproject tenCent

CrawlSpider创建:

scrapy genspider -t crawl crawl_tencent "hr.tencent.com"

CrawlSpider继承于Spider类,除了继承过来的属性外(name、allow_domains),还提供了新的属性和方法:

LinkExtractor

from scrapy.linkextractors import LinkExtractor
LinkExtractor(allow=r'start=\d+')

通过实例化LinkExtractor提取链接

主要参数

allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。

rules

Rule(LinkExtractor(allow=r'start=\d+'), callback='parse_tencent', follow=True),

在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。

如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用

主要参数

link_extractor:是一个Link Extractor对象,用于定义需要提取的链接
callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数。注意:当编写爬虫规则时,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为None,follow 默认设置为True ,否则默认为False。

使用CrawlSpider爬取信息

1.编写item文件

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass TencentItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()# 职位名称position_name = scrapy.Field()# 详情链接position_link = scrapy.Field()# 职位类别position_type = scrapy.Field()# 职位人数position_number = scrapy.Field()# 职位地点work_location = scrapy.Field()# 发布时间publish_times = scrapy.Field()# 工作职责position_duty = scrapy.Field()# 工作要求position_require = scrapy.Field()class DetailItem(scrapy.Item):# 工作职责position_duty = scrapy.Field()# 工作要求position_require = scrapy.Field()

2.编写crawlspider文件

# -*- coding: utf-8 -*-
import scrapy
from tenCent.items import TencentItem
from tenCent.items import DetailItem
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Ruleclass CrawlTencentSpider(CrawlSpider):name = 'crawl_tencent'allowed_domains = ['hr.tencent.com']start_urls = ['https://hr.tencent.com/position.php']'''rule LinkExtractor规则:allow:根据正则表达式匹配链接callback:回调函数follow:是否提取跟进页(链接套链接)'''rules = (Rule(LinkExtractor(allow=r'start=\d+'), callback='parse_tencent', follow=True),# 从上面的规则传递下一个Rule(LinkExtractor(allow=r'position_detail\.php\?id=\d+'), callback='parse_detail', follow=False),)def parse_tencent(self, response):print('start……')node_list = response.xpath('//tr[@class="even"] | //tr[@class="odd"]')# 选取所有标签tr 且class属性等于even或odd的元素#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()for node in node_list:item = TencentItem()item['position_name'] = node.xpath('./td[1]/a/text()').extract_first()  # 获取第一个td标签下a标签的文本item['position_link'] = node.xpath('./td[1]/a/@href').extract_first()  # 获取第一个td标签下a标签href属性item['position_type'] = node.xpath('./td[2]/text()').extract_first()  # 获取第二个td标签下文本item['position_number'] = node.xpath('./td[3]/text()').extract_first()  # 获取第3个td标签下文本item['work_location'] = node.xpath('./td[4]/text()').extract_first()  # 获取第4个td标签下文本item['publish_times'] = node.xpath('./td[5]/text()').extract_first()  # 获取第5个td标签下文本yield itemdef parse_detail(self, response):item = DetailItem()item['position_duty'] = ''.join(response.xpath('//ul[@class="squareli"]')[0].xpath('./li/text()').extract())  # 转化为字符串item['position_require'] = ''.join(response.xpath('//ul[@class="squareli"]')[1].xpath('./li/text()').extract())  # 转化为字符串yield item

3.建立pipeline文件

# -*- 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.htmlimport json
from .items import TencentItem
from .items import DetailItemclass TencentPipeline(object):def open_spider(self, spider):"""# spider (Spider 对象) – 被开启的spider# 可选实现,当spider被开启时,这个方法被调用。:param spider::return:"""self.file = open('tencent.json', 'w', encoding='utf-8')json_header = '{ "tencent_info":['self.count = 0self.file.write(json_header)  # 保存到文件def close_spider(self, spider):"""# spider (Spider 对象) – 被关闭的spider# 可选实现,当spider被关闭时,这个方法被调用:param spider::return:"""json_tail = '] }'self.file.seek(self.file.tell() - 1)  # 定位到最后一个逗号self.file.truncate()  # 截断后面的字符self.file.write(json_tail)  # 添加终止符保存到文件
        self.file.close()def process_item(self, item, spider):"""# item (Item 对象) – 被爬取的item# spider (Spider 对象) – 爬取该item的spider# 这个方法必须实现,每个item pipeline组件都需要调用该方法,# 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。:param item::param spider::return:"""# print('item=',dict(item))if isinstance(item, TencentItem):print('--'*20)content = json.dumps(dict(item), ensure_ascii=False, indent=2) + ","  # 字典转换json字符串self.count += 1print('content', self.count)self.file.write(content)  # 保存到文件'''return item后,item会根据优先级传递到下一个管道DetailPipeline处理此段代码说明当实例不属于TencentItem时,放弃存储json,直接传递到下一个管道处理return放在if外面,如果写在if里面item在不属于TencentItem实例后,item会终止传递,造成detail数据丢失'''return itemclass DetailPipeline(object):def open_spider(self, spider):"""# spider (Spider 对象) – 被开启的spider# 可选实现,当spider被开启时,这个方法被调用。:param spider::return:"""self.file = open('detail.json', 'w', encoding='utf-8')json_header = '{ "detail_info":['self.count = 0self.file.write(json_header)  # 保存到文件def close_spider(self, spider):"""# spider (Spider 对象) – 被关闭的spider# 可选实现,当spider被关闭时,这个方法被调用:param spider::return:"""json_tail = '] }'self.file.seek(self.file.tell() - 1)  # 定位到最后一个逗号self.file.truncate()  # 截断后面的字符self.file.write(json_tail)  # 添加终止符保存到文件
        self.file.close()def process_item(self, item, spider):"""# item (Item 对象) – 被爬取的item# spider (Spider 对象) – 爬取该item的spider# 这个方法必须实现,每个item pipeline组件都需要调用该方法,# 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。:param item::param spider::return:"""# print('item=',dict(item))if isinstance(item, DetailItem):'''得到item,判断item实例属于DetailItem,存储json文件如果不属于,直接return item到下一个管道'''print('**' * 30)content = json.dumps(dict(item), ensure_ascii=False, indent=2) + ","  # 字典转换json字符串self.count += 1print('content', self.count)self.file.write(content)  # 保存到文件return item

4.设置settiing

#1、项目名称,默认的USER_AGENT由它来构成,也作为日志记录的日志名
BOT_NAME = 'tenCent'
# 2、爬虫应用路径
SPIDER_MODULES = ['tenCent.spiders']
NEWSPIDER_MODULE = 'tenCent.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = '"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"'  # 头部信息,反爬# Obey robots.txt rules
ROBOTSTXT_OBEY = True# log日志
LOG_FILE = 'tencent.log'
LOG_LEVEL = 'DEBUG'
LOG_ENCODING = 'utf-8'
LOG_DATEFORMAT='%m/%d/%Y %H:%M:%S %p'ITEM_PIPELINES = {'tenCent.pipelines.TencentPipeline': 300,'tenCent.pipelines.DetailPipeline':400
}

5.执行程序

scrapy crawl crawl_tencent

tencent.log

tencent.json

detail.json

转载于:https://www.cnblogs.com/xiao-apple36/p/9027326.html

Scrapy框架——CrawlSpider爬取某招聘信息网站相关推荐

  1. 【python爬虫02】使用Scrapy框架爬取拉勾网招聘信息

    使用Scrapy框架爬取拉勾网招聘信息 最近接触了Scrapy爬虫框架,简单写了个爬虫爬取拉钩网的招聘信息,加深对Scrapy框架的理解,不得不说Scrapy框架其实还是蛮方便的,就像爬虫流水线一样, ...

  2. scrapy爬取——阿里招聘信息

    scrapy爬取--阿里招聘信息 爬取网站地址: https://job.alibaba.com/zhaopin/positionList.htm 1.创建项目 进入项目目录 输入cmd进入都是窗口创 ...

  3. 使用Scrapy框架,爬取b站番剧信息。

    使用Scrapy框架,爬取b站番剧信息. 感觉好久没写爬虫的,今天看了在b站浏览了一会儿,发现b站有很多东西可以爬取的,比如首页的排行榜,番剧感觉很容易找到数据来源的,所以就拿主页的番剧来练练手的. ...

  4. python3 scrapy实战:爬取拉勾网招聘数据至数据库(反爬虫)

    首先注明:感谢拉勾网提供的权威.质量的数据,本人抱着学习的态度,不愿增加其服务器负担,与dos攻击. 由于后面准备做一个大一点的数据分析项目,所以前提需要获取大量的有质量和权威的信息,其中一个获取点便 ...

  5. 使用python3.7中的scrapy框架,爬取起点小说

    这几天在学习scrapy框架,感觉有所收获,便尝试使用scrapy框架来爬取一些数据,对自己阶段性学习进行一个小小的总结 本次爬取的目标数据是起点中文网中的免费作品部分,如下图: 本次一共爬取了100 ...

  6. Python搭建代理池爬取拉勾网招聘信息

    先来看一张图了解下爬虫 实现功能 多线程爬取拉勾网招聘信息 维护代理 ip 池 搭建 node 服务器 Taro 使用 echarts 做数据分析 1.多线程爬取拉勾网招聘信息 Tip:涉及知识 1. ...

  7. 什么你还不知道招聘信息,小唐来教你——最新2021爬取拉勾网招聘信息(一)

    文章目录 前言 一.准备我们的库 二.分析分析 三. 代码 四.数据展示 小唐的心路历程 上一篇:没有啦! 下一篇:什么你还不知道招聘信息,小唐来教你--最新2021爬取拉勾网招聘信息(二) 前言 有 ...

  8. 什么你还不知道招聘信息,小唐来教你——最新2021爬取拉勾网招聘信息(二)

    文章目录 前言 一.准备我们的库 二.数据清洗 三.核密度图及词云制作 四.完整代码 五.扩展 上一篇:什么你还不知道招聘信息,小唐来教你--最新2021爬取拉勾网招聘信息(一) 下一篇:没有拉! 前 ...

  9. 手把手教你使用scrapy框架来爬取北京新发地价格行情(理论篇)

    点击上方"Python爬虫与数据挖掘",进行关注 回复"书籍"即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 博观而约取,厚积而薄发. 大家好! ...

  10. Python爬虫实战之一 - 基于Requests爬取拉勾网招聘信息,并保存至本地csv文件

    Python爬虫实战之二 - 基于Requests抓取拉勾网招聘信息 ---------------readme--------------- 简介:本人产品汪一枚,Python自学数月,对于小白,本 ...

最新文章

  1. python表白程序-用Python做一个表白小姐姐的程序
  2. shell 创建文件_如何在shell脚本中创建与shell脚本同目录或者同相对路径的文件夹或者文件?...
  3. 【Phpstorm】Property accessed via magic method
  4. hdu 3999The order of a Tree
  5. 京东sdk调用实例_Apache ShardingSphere(Incubating)对接京东白条实战
  6. PV操作经典例题——和尚打水
  7. 解决魅族手机不输出Log日志 或者输出部分日志问题
  8. 微信推出“微信圈子”,玩起来原来这么爽?
  9. 《灰故事》:他用曲笔描绘着我们
  10. AJAX、Json介绍
  11. jquery实现星星闪烁功能
  12. 计算机 存储体 存储单元 存储元 存储字 存储字长的联系
  13. 极速办公(ppt)文字如何设置斜体
  14. ts15_Forecast multiple seas_mSTL_make_subplot_rMSPE_UCM_date format_NeuralProphet_changepoint_StateS
  15. 电路分析 笔记整理(模拟电子电路)
  16. jpg怎么转换doc
  17. elementUI日期时间控件控制选择时间区间不超过一个月
  18. Linux内核完全注释 阅读笔记:2.4、控制器和控制卡
  19. 新寓言——没有窝的猪
  20. lunix remount u盘_linux下U盘、硬盘自动挂载

热门文章

  1. JSP教程第6讲笔记
  2. java图片转ASCII码_将图片转化成对应的Ascii字符图片
  3. tensorflow:卷积函数----tf.nn.conv2d
  4. 如何取消恶心的chrome浏览器被360篡改劫持问题
  5. C++构造函数详解(复制构造函数)
  6. 2021-08-12初识maven
  7. FISCO BCOS Failed to connect to nodes: [ ssl hanshake failed:/192.168.64.131:20200]
  8. 零知识证明 一文看懂 zkSNARK
  9. mysql数据同步到ElasticSearch中 之 logstash
  10. 小米系统wifi服务器,如何将小米8se(MIUI10系统)设置wifi仅连2.4赫兹