Scrapy框架——CrawlSpider类爬虫案例
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
每个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对象,用于定义需要提取的链接。
以下是案例代码:
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类爬虫案例的更多相关文章
- python爬虫之Scrapy框架(CrawlSpider)
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬去进行实现的(Request模块回调) 方法二:基于CrawlSpi ...
- 爬虫Scrapy框架-Crawlspider链接提取器与规则解析器
Crawlspider 一:Crawlspider简介 CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能.其中最显著 ...
- 网络爬虫之scrapy框架(CrawlSpider)
一.简介 CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能之外,还派生了其自己独有的更强大的特性和功能.其中最显著的功能就是"LinkExtractor ...
- 13.CrawlSpider类爬虫
1.CrawlSpider介绍 Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 此案例采用的是CrawlSpider类实现爬虫. 它是Spider的派生类,Spider类的设 ...
- 全栈爬取-Scrapy框架(CrawlSpider)
引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法 ...
- Scrapy框架——CrawlSpider爬取某招聘信息网站
CrawlSpider Scrapy框架中分两类爬虫,Spider类和CrawlSpider类. 它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页, 而Craw ...
- Scrapy框架-CrawlSpider
目录 1.CrawlSpider介绍 2.CrawlSpider源代码 3. LinkExtractors:提取Response中的链接 4. Rules 5.重写Tencent爬虫 6. Spide ...
- python学习之-用scrapy框架来创建爬虫(spider)
scrapy简单说明 scrapy 为一个框架 框架和第三方库的区别: 库可以直接拿来就用, 框架是用来运行,自动帮助开发人员做很多的事,我们只需要填写逻辑就好 命令: 创建一个 项目 : cd 到需 ...
- scrapy的CrawlSpider类
了解CrawlSpider 踏实爬取一般网站的常用spider,其中定义了一些规则(rule)来提供跟进link的方便机制,也许该spider不适合你的目标网站,但是对于大多数情况是可以使用的.因此, ...
随机推荐
- tensorflow的save和restore
使用tensorflow中的save和restore可以对模型进行保存和恢复 import tensorflow as tf v1 = tf.Variable(tf.random_normal([1, ...
- CMake Error at cmake/OpenCVUtils.cmake
CMake Error at cmake/OpenCVUtils.cmake:1047 (message): Failed to download . Status= Call Stack (most ...
- Java编译时多态和运行时多态
来源:https://blog.csdn.net/wendizhou/article/details/73733061 编译时多态:主要是方法的重载,通过参数列表的不同来区分不同的方法. 运行时多态: ...
- 阿里大于发送短信(java)
一.短信签名设置 1.短信签名是什么? 签名是在短信内容开始或者末尾跟的品牌或者应用名称,设置签名有一下几个好处:增加品牌的曝光度,增强用户的记忆让用户能更清楚的知道正在使用的应用. 2.签名可不可以 ...
- Bootstrap Popover
[Bootstrap Popover] 1.设置一个popover需要添加以下设置: 1)data-toggle="popover" 2)title="Example p ...
- webservice客户端 get delete post 请求
package com.cn.eport.util.common; import java.io.IOException; import java.util.List; import org.apac ...
- python全栈开发 什么是python python命名及循环
python全栈 一. python介绍: 1. python起源 2. 主要应用领域; web,人工智能,云计算,系统运维. 1.1 python是一门什么语言? python是一 ...
- oracle数据库连接不上
Oracle数据库1521端口telnet不通 现象:服务器的ip地址可以ping通,但是安装oracle过程中的指定的“1521”端口telnet不通过 解决办法:1.确保防火墙对1521端口开启: ...
- 二进制中1的个数(python)
题目描述 输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. # -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): ...
- Docker 网络不通的解决方法
表现是: docker主机内部网络正常,与其它主机的连接失效,其它主机不能连接docker主机上映射的端口,docker内部也无法连接外部主机. 执行docker info,可以看到一些警告. 可在不 ...