如何使用Scrapy递归爬取子页面

3
基本上,我正在尝试爬取一个带有一组类别的页面,抓取每个类别的名称,跟随与每个类别相关联的子链接到一个带有一组子类别的页面,抓取它们的名称,然后跟随每个子类别到其相关页面并检索文本数据。最后,我想输出一个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()
            }

如果可以,请给我们网站的地址。 - parik
1个回答

6

我不熟悉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函数中,您可以从元数据中获取类别名称,并从网页收集子类别数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接