首页 > 解决方案 > Scrapy - 选择和抓取特定类型的站点地图节点

问题描述

是我正在抓取的网站的站点地图。第 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

标签: pythonxmlscrapyweb-crawlersitemap

解决方案


您不需要使用SitemapSpider,只需使用正则表达式和标准蜘蛛。

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)

推荐阅读