【问题标题】:How to recursively crawl subpages with Scrapy如何使用 Scrapy 递归爬取子页面
【发布时间】:2017-05-31 19:57:52
【问题描述】:

所以基本上我正在尝试使用一组类别抓取一个页面,抓取每个类别的名称,按照与每个类别关联的子链接到具有一组子类别的页面,抓取它们的名称,然后按照每个子类别到他们的关联页面并检索文本数据。最后,我想输出一个格式有点像的 json 文件:

  1. 类别 1 名称
    • 子类别 1 名称
      • 来自该子类别页面的数据
    • 子类别 n 名称
      • 来自此页面的数据
  2. 类别 n 名称
    • 子类别 1 名称
      • 来自子类别 n 页面的数据

等等

最终我希望能够将这些数据与 ElasticSearch 一起使用

我几乎没有任何使用 Scrapy 的经验,这就是我目前所拥有的(只是从第一页刮掉类别名称,我不知道从这里做什么)...根据我的研究,我认为我需要使用 CrawlSpider 但不确定这意味着什么。我也被建议使用 BeautifulSoup。任何帮助将不胜感激。

class randomSpider(scrapy.Spider):
    name = "helpme"
    allowed_domains = ["example.com"]
    start_urls = ['http://example.com/categories',]

    def parse(self, response):
        for i in response.css('div.CategoryTreeSection'):
            yield {
                'categories': i.css('a::text').extract_first()
            }

【问题讨论】:

  • 如果可以的话,给我们网站地址

标签: python beautifulsoup scrapy web-crawler scrapy-spider


【解决方案1】:

不熟悉 ElasticSearch,但我会像这样构建一个爬虫:

class randomSpider(scrapy.Spider):
    name = "helpme"
    allowed_domains = ["example.com"]
    start_urls = ['http://example.com/categories',]

    def parse(self, response):
        for i in response.css('div.CategoryTreeSection'):
            subcategory = i.css('Put your selector here') # This is where you select the subcategory url
            req = scrapy.Request(subcategory, callback=self.parse_subcategory)
            req.meta['category'] = i.css('a::text').extract_first()
            yield req

    def parse_subcategory(self, response):
        yield {
            'category' : response.meta.get('category')
            'subcategory' : response.css('Put your selector here') # Select the name of the subcategory
            'subcategorydata' : response.css('Put your selector here') # Select the data of the subcategory
        }

您收集子类别 URL 并发送请求。此请求的响应将在parse_subcategory 中打开。在发送此请求时,我们在元数据中添加类别名称。

parse_subcategory 函数中,您从元数据中获取类别名称并从网页中收集子类别数据。

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多