首页 > 解决方案 > 解析方法的 Scrapy 参数

问题描述

我正在用 Python Scrapy 编写一个网络爬虫,它爬过标签目录的多个页面并获取所有标签及其文章。

所以我得到了这个解析方法,蜘蛛在每个页面中运行。

def parse_word(self, response):

     # look for all tags on this site
     tagscount = response.xpath('someXpath').extract()

     # check if there is a nextPage
     nextPage = response.css('somecssSelector').extract()
     lastPage = response.css('somecssSelector').extract()

     # Open every tagsite and crawl it if all tags are gained
     if not nextPage or lastPage:

         for tag in tagscount:

             # call parse method for article crawling
             data = scrapy.Request(url=tag, callback=self.parse_subpage)
             yield data

     # If there is a nextPage with tags request with this method recursively
     else:

         # a little bit of formatting for linktype
         nextPageStr = str(nextPage)
         cutNextPageStr = nextPageStr.replace("[","")
         cutNextPageStr = cutNextPageStr.replace("]", "")
         cutNextPageStr = cutNextPageStr.replace("'", "")
         link = urljoin(response.url, cutNextPageStr)

         # Call this method again --> here i want to set a parameter tagscount or something like this
         data = scrapy.Request(url=link, callback=self.parse_word)
         yield data

在其他部分,我想为 parse_word 方法提供获得的标签,但整个方法只采用最后一个站点的标签。

谁能帮我?

标签: pythonparsingmethodsparametersscrapy

解决方案


要提出替代解决方案,您可以使用蜘蛛中间件来执行计数,该中间件将存储在请求/响应元字典中。

从某种意义上说,计数的责任与从页面中选择元素的责任是分开的,这更简洁一些。


推荐阅读