【问题标题】:Scrapy - Selecting and crawling a specific type of sitemap nodesScrapy - 选择和抓取特定类型的站点地图节点
【发布时间】:2019-07-08 07:22:02
【问题描述】:

This 是我正在抓取的网站的站点地图。第 3 个和第 4 个 <sitemap> 节点具有指向项目详细信息的 url。有没有办法只将爬取逻辑应用于那些 节点? (比如通过索引选择它们)

class MySpider(SitemapSpider):

    name = 'myspider'

    sitemap_urls = [
        'https://www.dfimoveis.com.br/sitemap_index.xml',
    ]

    sitemap_rules = [
        ('/somehow targeting the 3rd and 4th node', 'parse_item')
    ]


    def parse_item(self, response):
        # scraping the item

【问题讨论】:

  • 节点有项目详细信息 - 没有此类详细信息 - 它们在 loc 项目中包含 detalhes。你想按那个词过滤吗?
  • @RomanPerekhrest 我的意思是他们有指向项目详细信息的 url。抱歉不清楚,我正在编辑我的帖子。我正在尝试从这些节点内的 url 中抓取项目详细信息。
  • 澄清什么是item details
  • @RomanPerekhrest 第三和第四节点内的每个 url 都是一个项目。如果我只能选择那些节点,我将向 url 发送请求并抓取项目详细信息。

标签: python xml scrapy web-crawler sitemap


【解决方案1】:

您不需要使用 SitemapSpider,只需使用 regex 和标准蜘蛛。

def start_requests(self):
    sitemap = 'https://www.dfimoveis.com.br/sitemap_index.xml'
    yield scrapy.Request(url=sitemap, callback=self.parse_sitemap)

def parse_sitemap(self, response):
    sitemap_links = re.findall(r"<loc>(.*?)</loc>", response.text, re.DOTALL)
    sitemap_links = sitemap_links[2:4]  # Only 3rd and 4th nodes.
        for sitemap_link in sitemap_links:
            yield scrapy.Request(url=sitemap_link, callback=self.parse)

【讨论】:

  • 第3和第4节点不应该是“sitemap_links[2:4]”吗?
【解决方案2】:

Scrapy 的 Spider 子类,包括 SitemapSpider 旨在使非常常见的场景变得非常简单。

你想做一些不常见的事情,所以你应该阅读SitemapSpider的源代码,试着理解它的作用,或者子类SitemapSpider覆盖你想要改变的行为,或者直接编写你自己的基于SitemapSpider的代码从零开始爬虫。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多