赞
踩
蜘蛛:
一,前言:
在scrapy中蜘蛛定义了爬取方法(请求&解析)以及爬取某个(或某些)网页(URL)的一些操作。
生成一个蜘蛛项目的方法,执行cmd命令:scrapy genspider lagou www.lagou.com(scrapy genspider项目名域名)
温馨提示:在生成的蜘蛛时,其实有4中模版,如如果不特指就默认为基本,就像上面的genspider一样没有指定则默认使用基本的,它还有三个模版为:crawlspider,csvfeedspider和xmlfeedspider。
其中蜘蛛为最基本的类,所有蜘蛛模版都要继承它(基本就是直接继承蜘蛛类)
蜘蛛类主要用到的函数及调用顺序为:
二,分析:
一个蜘蛛类主要用到的函数方法和调用顺序为:
1)初始化():初始化爬虫名字和start_urls列表。
- def __init__(self, name=None, **kwargs):
- if name is not None:
- self.name = name
- elif not getattr(self, 'name', None):
- raise ValueError("%s must have a name" % type(self).__name__)
- self.__dict__.update(kwargs)
- if not hasattr(self, 'start_urls'):
- self.start_urls = []
2)start_requests(),蜘蛛发起请求的开始,它执行会调用make_requests_from_url(),生成请求对象交给Scrapy下载并返回响应给具体的处理函数处理
- def start_requests(self):
- cls = self.__class__
- if method_is_overridden(cls, Spider, 'make_requests_from_url'):
- warnings.warn(
- "Spider.make_requests_from_url method is deprecated; it "
- "won't be called in future Scrapy releases. Please "
- "override Spider.start_requests method instead (see %s.%s)." % (
- cls.__module__, cls.__name__
- ),
- )
- for url in self.start_urls:
- yield self.make_requests_from_url(url)
- else:
- for url in self.start_urls:
- yield Request(url, dont_filter=True)
-
- def make_requests_from_url(self, url):
- """ This method is deprecated. """
- return Request(url, dont_filter=True)
3)parse(),具体处理响应响应的处理函数(即分析页面),其中在start_request()中,如果不知道callback则默认调用parse()。同时该函数可以自行定义,调用时使用callback回调即可,记得回调参数使用的是函数地址和不是函数方法,即只需要给函数方法名,不要带()。
提示:这个方法要根据我们自己的爬取需求自己设计,解析响应完成之后,并返回项目或请求(需指定回调函数).Item传给项目和管道处理,请求交由Scrapy下载,并由指定的回调函数处理,一直进行循环,直到处理完所有的数据为止。
蜘蛛源码:
- """
- Base class for Scrapy spiders
- See documentation in docs/topics/spiders.rst
- """
- import logging
- import warnings
-
- from scrapy import signals
- from scrapy.http import Request
- from scrapy.utils.trackref import object_ref
- from scrapy.utils.url import url_is_from_spider
- from scrapy.utils.deprecate import create_deprecated_class
- from scrapy.exceptions import ScrapyDeprecationWarning
- from scrapy.utils.deprecate import method_is_overridden
-
- #所有爬虫的基类,用户定义的爬虫必须从这个类继承
- class Spider(object_ref):
- """Base class for scrapy spiders. All spiders must inherit from this
- class.
- """
-
- #1、定义spider名字的字符串。spider的名字定义了Scrapy如何定位(并初始化)spider,所以其必须是唯一的。
- #2、name是spider最重要的属性,而且是必须的。一般做法是以该网站的域名来命名spider。例如我们在爬取豆瓣读书爬虫时使用‘name = "douban_book_spider"’
- name = None
- custom_settings = None
-
- #初始化爬虫名字和start_urls列表。上面已经提到。
- def __init__(self, name=None, **kwargs):
- #初始化爬虫名字
- if name is not None:
- self.name = name
- elif not getattr(self, 'name', None):
- raise ValueError("%s must have a name" % type(self).__name__)
- self.__dict__.update(kwargs)
-
- #初始化start_urls列表,当没有指定的URL时,spider将从该列表中开始进行爬取。 因此,第一个被获取到的页面的URL将是该列表之一,后续的URL将会从获取到的数据中提取。
- if not hasattr(self, 'start_urls'):
- self.start_urls = []
-
- @property
- def logger(self):
- logger = logging.getLogger(self.name)
- return logging.LoggerAdapter(logger, {'spider': self})
-
- def log(self, message, level=logging.DEBUG, **kw):
- """Log the given message at the given log level
- This helper wraps a log call to the logger within the spider, but you
- can use it directly (e.g. Spider.logger.info('msg')) or use any other
- Python logger too.
- """
- self.logger.log(level, message, **kw)
-
- @classmethod
- def from_crawler(cls, crawler, *args, **kwargs):
- spider = cls(*args, **kwargs)
- spider._set_crawler(crawler)
- return spider
-
- def set_crawler(self, crawler):
- warnings.warn("set_crawler is deprecated, instantiate and bound the "
- "spider to this crawler with from_crawler method "
- "instead.",
- category=ScrapyDeprecationWarning, stacklevel=2)
- assert not hasattr(self, 'crawler'), "Spider already bounded to a " \
- "crawler"
- self._set_crawler(crawler)
-
- def _set_crawler(self, crawler):
- self.crawler = crawler
- self.settings = crawler.settings
- crawler.signals.connect(self.close, signals.spider_closed)
-
- #该方法将读取start_urls列表内的地址,为每一个地址生成一个Request对象,并返回这些对象的迭代器。
- #注意:该方法只会调用一次。
- def start_requests(self):
- cls = self.__class__
- if method_is_overridden(cls, Spider, 'make_requests_from_url'):
- warnings.warn(
- "Spider.make_requests_from_url method is deprecated; it "
- "won't be called in future Scrapy releases. Please "
- "override Spider.start_requests method instead (see %s.%s)." % (
- cls.__module__, cls.__name__
- ),
- )
- for url in self.start_urls:
- yield self.make_requests_from_url(url)
- else:
- for url in self.start_urls:
- yield Request(url, dont_filter=True)
-
- #1、start_requests()中调用,实际生成Request的函数。
- #2、Request对象默认的回调函数为parse(),提交的方式为get。
- def make_requests_from_url(self, url):
- """ This method is deprecated. """
- return Request(url, dont_filter=True)
-
- #默认的Request对象回调函数,处理返回的response。
- #生成Item或者Request对象。这个类需要我们自己去实现。
- def parse(self, response):
- raise NotImplementedError
-
- @classmethod
- def update_settings(cls, settings):
- settings.setdict(cls.custom_settings or {}, priority='spider')
-
- @classmethod
- def handles_request(cls, request):
- return url_is_from_spider(request.url, cls)
-
- @staticmethod
- def close(spider, reason):
- closed = getattr(spider, 'closed', None)
- if callable(closed):
- return closed(reason)
-
- def __str__(self):
- return "<%s %r at 0x%0x>" % (type(self).__name__, self.name, id(self))
-
- __repr__ = __str__
-
-
- BaseSpider = create_deprecated_class('BaseSpider', Spider)
-
-
- class ObsoleteClass(object):
- def __init__(self, message):
- self.message = message
-
- def __getattr__(self, name):
- raise AttributeError(self.message)
-
- spiders = ObsoleteClass(
- '"from scrapy.spider import spiders" no longer works - use '
- '"from scrapy.spiderloader import SpiderLoader" and instantiate '
- 'it with your project settings"'
- )
-
- # Top-level imports
- from scrapy.spiders.crawl import CrawlSpider, Rule
- from scrapy.spiders.feed import XMLFeedSpider, CSVFeedSpider
- from scrapy.spiders.sitemap import SitemapSpider
-
- 作者:小怪聊职场
- 链接:https://www.jianshu.com/p/d492adf17312
- 來源:简书
- 简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。