【问题标题】:How to use sitemap of urls in scrapy spider?如何在scrapy蜘蛛中使用网址的站点地图?
【发布时间】:2017-10-10 15:37:03
【问题描述】:

我想创建一个基于网页的sitemap.xml 抓取网址的蜘蛛。所以我没有start_urls。我想确定使用sitemap.xml 抓取哪些网址。

我考虑过添加一个方法 _parse_sitemap 并使用 requestslxml 解析它,但这可能有点过头了。

是否有一些内置方法可以获取 <loc> 标签内的所有 url?

到目前为止我做了什么:

Spider 获取一个 url 和 meta = {'sitemap':True},因此 parse 方法知道它必须根据站点地图中的 url 调用 _parse_sitemap 其中 yields Request 对象。

import scrapy
from scrapy import Request


class MainSpider(scrapy.Spider):
    name = 'main_spider'
    allowed_domains = ['www.example.com']
    sitemap = 'www.example.com/sitemap.xml'
    start_urls = [sitemap]

    def start_requests(self):
        yield Request(url=self.sitemap,meta={'sitemap':True})

    def parse(self, response):
        if response.meta.get('sitemap'):
            self._parse_sitemap(response)
        else:
            # parse normal url

    def _parse_sitemap(self, response):
        # how to get urls?
        urls = []
        for url in urls:
            yield Request(url=url,callback=self.parse)

这只是一个xml,所以我认为我不应该使用SitemapSpider。你有什么建议吗?如您所见,我不知道如何在_parse_sitemap spider 中解析urls

【问题讨论】:

  • 为什么你认为你不应该使用 SitemapSpider,因为你只有一个文件?您的蜘蛛可能非常简单,就像文档中的第一个示例:doc.scrapy.org/en/latest/topics/…
  • 您可以简单地使用 SgmlLinkExtractor。它将提供页面中的所有链接。在下面使用 Imports from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.contrib.spiders import CrawlSpider, Rule 在类中添加以下行并在回调中指定您的函数,它将响应所有 url 规则 = (Rule(SgmlLinkExtractor(), callback ='parse_url', follow=False), )

标签: xml scrapy web-crawler screen-scraping sitemap


【解决方案1】:

您可以简单地使用 SgmlLinkExtractor。它将给出页面中的所有链接。

在 Imports 下面使用

from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule

在类中添加以下行并在回调中指定您的函数,它将响应所有 url

rules = (Rule(SgmlLinkExtractor(), callback='_parse_sitemap', follow=False), )

【讨论】:

    【解决方案2】:

    由于 SgmlLinkExtractor 现在已弃用,因此应使用 LxmlLinkExtractor。提供更多关于它们之间区别的信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2015-11-18
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      相关资源
      最近更新 更多