scrapy中Crawlspider的用法

Crawlspider创建

  • scrapy genspider -t crawl baidu www.baidu.com

Crawlspider用法

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
import re

class CfSpider(CrawlSpider):
    name = 'cf'
    allowed_domains = ['cbirc.gov.cn/']
    start_urls = ['http://www.cbirc.gov.cn/cn/view/pages/index/jiansuo.html?keyWords=%E8%A1%8C%E6%94%BF%E5%A4%84%E7%BD%9A']

    # 定义提取url地址规则
    rules = (
        # 实例化Rule类
        # LinkExtractor 链接提取器,提取url地址(正则)
        # 提取后的url给parse()函数发送请求传参,所以在Crawlspider不能自己定义parse()函数,否则会覆盖
        # callback 提取出来的url地址的response会交给callback处理,如果不用提取数据的页面,则可以不用指定
        # follow 当前url地址的响应是否重新经过rules来我去url地址,如果为False则不会继续进入rules
        # Rule是同时进行的,之前不能传递数据
        Rule(LinkExtractor(allow=r'/cn/view/pages/ItemDetail.html?docId=\d+&itemId=4114&generaltype=9'), callback='parse_item', follow=False),
        Rule(LinkExtractor(allow=r'/cn/view/pages/ItemDetail.html?docId=\d+&itemId=4114&generaltype=9'), callback='parse_item', follow=True),
    )

    # parse函数
    def parse_item(self, response):
        item = dict()
        item['title'] = response.xpath('//input[@id="title"]/@value').get()
        return item

LinkExtractor更多常见参数

- allow: 满足括号中"正则表达式"的URL会被提取,如果为空,则全部匹配
- deny: 满足括号中"正则表达式"的URL一定不提取(优先级高于allow)
- allow_domains: 会被提取的链接的domains
- deny_domains: 一定不会被提取的domains
- restrict_xpath: 使用xpath表达式,和allow共同作用过滤链接,级xpath满足范围内的url地址会被提取(也可单独使用,定位到包含链接的div或a元素即可)

Spider.Rule 常见参数

link_extarctor: 是一个link Extractor对象,用于定义需要提取的链接
callback: 从link_extractor中每提取到链接时,参数所制定的值作为回调函数
follow:是一个布尔值,指定了根据该规则从response提取的链接是否需要跟进。
		如果callback为None,follow默认设置Ture,否则默认为False
process_links: 指定该spider中哪个函数将会被调用,从link_extractor中获取到链接列表时将会调用该函数,主要用于过滤url
peocess_resquest: 指定该spider中哪个函数将会被调用,该规则提取到的resquest时都会调用的函数,
用来过滤request

注意点

- 不指定callback函数的请求下,如果follow为true,满足该入了还会被继续请求
- 如果多个Rule都满足一个某一个url,会从rules中选择第一个满足进行操作
- url地址不完整,crawl会自动补充完整之后再请求
- rules中Rule()的callback之间是不能传递参数的,最终页面有全部数据时可用,否则自己在callback自己构造请求

get()/getall()和extract()/extract_first()

- 开篇明义:get() 、getall() 是新版本的方法,extract() 、extract_first()是旧版本的方法。

- 前者更好用,取不到就返回None,后者取不到就raise一个错误,推荐使用新方法,

- 对于scrapy.selector.unified.SelectorList对象,getall()==extract(),get()==extract_first()
- 对于scrapy.selector.unified.Selector对象,getall()==extract(),get()!=extract_first()
发布了54 篇原创文章 · 获赞 24 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43388615/article/details/105102812