【问题标题】:Scrapy crawl all sitemap linksScrapy 抓取所有站点地图链接
【发布时间】:2014-04-09 08:48:21
【问题描述】:

我想抓取固定站点的 sitemap.xml 中存在的所有链接。我遇到了 Scrapy 的 SitemapSpider。到目前为止,我已经提取了站点地图中的所有网址。现在我想通过站点地图的每个链接进行爬网。任何帮助都会非常有用。到目前为止的代码是:

class MySpider(SitemapSpider):
    name = "xyz"
    allowed_domains = ["xyz.nl"]
    sitemap_urls = ["http://www.xyz.nl/sitemap.xml"] 

    def parse(self, response):
        print response.url

【问题讨论】:

  • 如果您可以为该域发布一个有效的url,那么检查代码会更容易

标签: python scrapy web-crawler sitemap


【解决方案1】:

您需要添加sitemap_rules来处理抓取到的url中的数据,您可以创建任意多个。 例如,假设您有一个名为 http://www.xyz.nl//x/ 的页面,您想创建一个规则:

class MySpider(SitemapSpider):
    name = 'xyz'
    sitemap_urls = 'http://www.xyz.nl/sitemap.xml'
    # list with tuples - this example contains one page 
    sitemap_rules = [('/x/', parse_x)]

    def parse_x(self, response):
        sel = Selector(response)
        paragraph = sel.xpath('//p').extract()

        return paragraph

【讨论】:

  • 如果不指定规则,默认调用parse方法;我相信原帖在这方面是正确的
【解决方案2】:

基本上你可以创建新的请求对象来抓取由 SitemapSpider 创建的 url 并使用新的回调解析响应:

class MySpider(SitemapSpider):
    name = "xyz"
    allowed_domains = ["xyz.nl"]
    sitemap_urls = ["http://www.xyz.nl/sitemap.xml"] 

    def parse(self, response):
        print response.url
        return Request(response.url, callback=self.parse_sitemap_url)

    def parse_sitemap_url(self, response):
        # do stuff with your sitemap links

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多