Scrapy CrawlSpider的介绍

Scrapy_CrawlSpider的介绍

image-20220628234425367

在Scrapy中Spider是所有爬虫的基类,而CrawSpiders就是Spider的派生类。

适用于先爬取start_url列表中的网页,再从爬取的网页中获取link并继续爬取的工作。运行图如下

image-20220707161423706

1 创建CrawlSpider

scrapy genspider -t crawl 爬虫名 (allowed_url)

2 使用CrawlSpider中核心的2个类对象

2.1 Rule对象

Rule类与CrawlSpider类都位于scrapy.contrib.spiders模块中

class scrapy.contrib.spiders.Rule( 
    link_extractor,         
    callback=None,
    cb_kwargs=None,
    follow=None,
    process_links=None,
    process_request=None) 

参数含义:

  • link_extractor为LinkExtractor,用于定义需要提取的链接

  • callback参数:当link_extractor获取到链接时参数所指定的值作为回调函数

    注意 回调函数尽量不要用parse方法,crawlspider已使用了parse方法

  • follow:指定了根据该规则从response提取的链接是否需要跟进。当callback为None,默认值为True

  • process_links:主要用来过滤由link_extractor获取到的链接

  • process_request:主要用来过滤在rule中提取到的request

2.2 LinkExtractors

顾名思义,链接提取器

2.2.1 作用

response对象中获取链接,并且该链接会被接下来爬取 每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象

2.2.2 使用
class scrapy.linkextractors.LinkExtractor(
  allow = (),
  deny = (),
  allow_domains = (),
  deny_domains = (),
  deny_extensions = None,
  restrict_xpaths = (),
  tags = ('a','area'),
  attrs = ('href'),
  canonicalize = True,
  unique = True,
  process_value = None
)

2.2.3 查看效果-shell中验证

首先运行

scrapy shell 'https://www.zhhbqg.com/1_1852/835564.html'

继续import相关模块:

from scrapy.linkextractors import LinkExtractor

提取当前网页中获得的链接

link = LinkExtractor(restrict_xpaths=(r'//a'))

调用LinkExtractor实例的extract_links()方法查询匹配结果

 link.extract_links(response)

2.2.4 查看效果 CrawlSpider版本
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from xiaoshuo.items import XiaoshuoItem


class XiaoshuoSpiderSpider(CrawlSpider):
  name = 'xiaoshuo_spider'
  allowed_domains = ['fhxiaoshuo.com']
  start_urls = ['http://www.fhxiaoshuo.com/read/33/33539/17829387.shtml']


  rules = [
    Rule(LinkExtractor(restrict_xpaths=(r'//div[@class="bottem"]/a[4]')), callback='parse_item'),]


  def parse_item(self, response):
    info = response.xpath("//div[@id='TXT']/text()").extract()
    it = XiaoshuoItem()
    it['info'] = info
    yield it


  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留不住的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值