• 高级深入--day33


    CrawlSpiders

    通过下面的命令可以快速创建 CrawlSpider模板 的代码:

    scrapy genspider -t crawl tencent tencent.com

    上一个案例中,我们通过正则表达式,制作了新的url作为Request请求参数,现在我们可以换个花样...

    class scrapy.spiders.CrawlSpider

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

    源码参考
    1. class CrawlSpider(Spider):
    2. rules = ()
    3. def __init__(self, *a, **kw):
    4. super(CrawlSpider, self).__init__(*a, **kw)
    5. self._compile_rules()
    6. #首先调用parse()来处理start_urls中返回的response对象
    7. #parse()则将这些response对象传递给了_parse_response()函数处理,并设置回调函数为parse_start_url()
    8. #设置了跟进标志位True
    9. #parse将返回item和跟进了的Request对象
    10. def parse(self, response):
    11. return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True)
    12. #处理start_url中返回的response,需要重写
    13. def parse_start_url(self, response):
    14. return []
    15. def process_results(self, response, results):
    16. return results
    17. #从response中抽取符合任一用户定义'规则'的链接,并构造成Resquest对象返回
    18. def _requests_to_follow(self, response):
    19. if not isinstance(response, HtmlResponse):
    20. return
    21. seen = set()
    22. #抽取之内的所有链接,只要通过任意一个'规则',即表示合法
    23. for n, rule in enumerate(self._rules):
    24. links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
    25. #使用用户指定的process_links处理每个连接
    26. if links and rule.process_links:
    27. links = rule.process_links(links)
    28. #将链接加入seen集合,为每个链接生成Request对象,并设置回调函数为_repsonse_downloaded()
    29. for link in links:
    30. seen.add(link)
    31. #构造Request对象,并将Rule规则中定义的回调函数作为这个Request对象的回调函数
    32. r = Request(url=link.url, callback=self._response_downloaded)
    33. r.meta.update(rule=n, link_text=link.text)
    34. #对每个Request调用process_request()函数。该函数默认为indentify,即不做任何处理,直接返回该Request.
    35. yield rule.process_request(r)
    36. #处理通过rule提取出的连接,并返回item以及request
    37. def _response_downloaded(self, response):
  • 相关阅读:
    Spring MVC的转发与重定向
    这玩意也太猛了!朋友们,我在此严正呼吁大家:端好饭碗,谨防 AI!
    webpack5 PWA解决Web App 项目网络离线情况没法访问情况
    南大通用数据库-Gbase-8a-学习-15-Gbase8a通过Dblink访问Gbase8a(95->86)
    mysql binlog的清理
    华为云云服务器云耀L实例评测 | 从零到一:华为云云耀云服务器L实例上手体验
    Echart 非apache 托管
    正厚干货 | Git客户端用户使用指南
    使用MFC创建一个SaleSystem
    数据结构—归并排序-C语言实现
  • 原文地址:https://blog.csdn.net/qq_41813416/article/details/133891549