Scrapy--CrawlSpider

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

此案例采用的是CrawlSpider类实现爬虫。

它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。如爬取大型招聘网站

创建项目

 scrapy startproject tencent #创建项目

创建模板

scrapy genspider crawl -t tencent 'hr.tencent.com'    #tencent为爬虫名称 hr.tencent.com为限制域

创建完会模板后会生成一个tencent.py的文件

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class TencentSpider(CrawlSpider):
name = 'tencent'
allowed_domains = ['tencent.com']
start_urls = ['http://tencent.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
Link Extractors 的目的很简单: 提取链接。
每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象。
LinkExtractors要实例化一次,并且 extract_links 方法会根据不同的 response 调用多次提取链接。
 主要参数: 
 allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。 
 deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。 
 allow_domains:会被提取的链接的domains。 
 deny_domains:一定不会被提取链接的domains。 
 restrict_xpaths:使用xpath表达式,和allow共同作用过滤链接。
rules

在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用。

参数介绍:
LinkExtractor:是一个Link Extractor对象,用于定义需要提取的链接。

callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数 
follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为None,follow 默认设置为True,否则默认为False。 
process_links:指定该spider中哪个的函数将会被调用,从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤。 
process_request:指定该spider中哪个的函数将会被调用, 该规则提取到每个request时都会调用该函数。 (用来过滤request)

以下是案例代码:

item文件

import scrapy

    class TencentItem(scrapy.Item):
# 职位
name = scrapy.Field()
# 详情链接
positionlink = scrapy.Field()
#职位类别
positiontype = scrapy.Field()
# 人数
peoplenum = scrapy.Field()
# 工作地点
worklocation = scrapy.Field()
# 发布时间
publish = scrapy.Field()

pipeline文件

import json
class TencentPipeline(object): def __init__(self):
self.filename = open("tencent.json", "w")
def process_item(self, item, spider):
text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
self.filename.write(text.encode("utf-8"))
return item
def close_spider(self, spider):
self.filename.close()

setting文件

BOT_NAME = 'tencent'

    SPIDER_MODULES = ['tencent.spiders']
NEWSPIDER_MODULE = 'tencent.spiders'
LOG_FILE = 'tenlog.log'
LOG_LEVEL = 'DEBUG'
LOG_ENCODING = 'utf-8' ROBOTSTXT_OBEY = True DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
} ITEM_PIPELINES = {
'tencent.pipelines.TencentPipeline': 300,
}

spider文件

# -*- coding: utf-8 -*-
import scrapy
# 导入链接匹配规则类,用来提取符合规则的链接
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from tencent.items import TencentItem class TenecntSpider(CrawlSpider):
name = 'tencent1'
# 可选,加上会有一个爬去的范围
allowed_domains = ['hr.tencent.com']
start_urls = ['http://hr.tencent.com/position.php?&start=0#a']
# response中提取 链接的匹配规则,得出是符合的链接
pagelink = LinkExtractor(allow=('start=\d+')) print (pagelink)
# 可以写多个rule规则
rules = [
# follow = True需要跟进的时候加上这句。
# 有callback的时候就有follow
# 只要符合匹配规则,在rule中都会发送请求,同是调用回调函数处理响应
# rule就是批量处理请求
Rule(pagelink, callback='parse_item', follow=True),
] # 不能写parse方法,因为源码中已经有了,回覆盖导致程序不能跑
def parse_item(self, response):
for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
# 把数据保存在创建的对象中,用字典的形式 item = TencentItem()
# 职位
# each.xpath('./td[1]/a/text()')返回的是列表,extract转为unicode字符串,[0]取第一个
item['name'] = each.xpath('./td[1]/a/text()').extract()[0]
# 详情链接
item['positionlink'] = each.xpath('./td[1]/a/@href').extract()[0]
# 职位类别
item['positiontype'] = each.xpath("./td[2]/text()").extract()[0]
# 人数
item['peoplenum'] = each.xpath('./td[3]/text()').extract()[0]
# 工作地点
item['worklocation'] = each.xpath('./td[4]/text()').extract()[0]
# 发布时间
item['publish'] = each.xpath('./td[5]/text()').extract()[0] # 把数据交给管道文件
yield item

这个样就实现了一个简单的CrawlSpider类爬虫

Scrapy框架——CrawlSpider类爬虫案例的更多相关文章

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

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

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

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

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

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

  4. 13.CrawlSpider类爬虫

    1.CrawlSpider介绍 Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 此案例采用的是CrawlSpider类实现爬虫. 它是Spider的派生类,Spider类的设 ...

  5. 全栈爬取-Scrapy框架(CrawlSpider)

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

  6. Scrapy框架——CrawlSpider爬取某招聘信息网站

    CrawlSpider Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页, 而Craw ...

  7. Scrapy框架-CrawlSpider

    目录 1.CrawlSpider介绍 2.CrawlSpider源代码 3. LinkExtractors:提取Response中的链接 4. Rules 5.重写Tencent爬虫 6. Spide ...

  8. python学习之-用scrapy框架来创建爬虫(spider)

    scrapy简单说明 scrapy 为一个框架 框架和第三方库的区别: 库可以直接拿来就用, 框架是用来运行,自动帮助开发人员做很多的事,我们只需要填写逻辑就好 命令: 创建一个 项目 : cd 到需 ...

  9. scrapy的CrawlSpider类

    了解CrawlSpider 踏实爬取一般网站的常用spider,其中定义了一些规则(rule)来提供跟进link的方便机制,也许该spider不适合你的目标网站,但是对于大多数情况是可以使用的.因此, ...

随机推荐

  1. cv2对图像进行旋转和放缩变换

    旋转: def get_image_rotation(image): #通用写法,即使传入的是三通道图片依然不会出错 height, width = image.shape[:2] center = ...

  2. Repeater - 重复器

    Repeater - 重复器,用来展示泛型集合中的数据 五大模板:1.HeaderTemplate - 头模板,加载时会在开始执行一次2.FooterTemplate - 脚模板,加载时会在最后执行一 ...

  3. JS-cookie和正则表达式

    一 cookie 1 什么是cookie? 会话跟踪技术 2 作用 验证身份,存储信息. 3 特点 大小限制,最多存4k: 每个域下只能存50个cookie: 有时间限制: 只能存放字符串: 只能访问 ...

  4. linux下WIFI的AP搜索、连接方法

    wpa_supplicant -Dwext -ieth1 -c/etc/wpa_supplicant.conf  &wpa_cli save_configwpa_cli reconfigure ...

  5. Linux下修改tab建为4个空格

    1.编辑 vim /etc/vim/vimrc 2.修改 set ts=4 set expandtab set autoindent 其实只要set ts=4 就ok了.

  6. css flex 兼容ios android--商品展示 添加购物车

    https://blog.csdn.net/u010035608/article/details/52711248 <!DOCTYPE html> <html> <hea ...

  7. Gradle 在Eclipse中的使用

    eclipse上gradle插件的安装 1)在Eclipse中选择Help -> Eclipse Marketplace…,输入buildship点击Go,然后选择Install安装Gradle ...

  8. sql 求max和min,但是第二大,第二小怎么算?

    利用子查询,但这样速度较慢. SELECT Baoming.id, Baoming.addtime AS '报名时间', CONCAT(Members.realname,Members.usernam ...

  9. vue-cli 配置 proxyTable pathRewrite

    vue-config-index.js中,proxyTable中的pathRewrite有什么用呢? 首先,在ProxyTable模块中设置了‘/api’,target中设置服务器地址,也就是接口的开 ...

  10. 9. Palindrome Number (考虑负数的情况)

    Determine whether an integer is a palindrome. Do this without extra space. long int reverse(int x) { ...