如何使用scrapy的XmlFeedSpider解析sitemap.xml文件?

mde*_*ous 2 python xml sitemap namespaces scrapy

我试图sitemap.xml使用scrapy 解析文件,站点地图文件就像下面的文件一样,只有更多的url节点。

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:video="http://www.sitemaps.org/schemas/sitemap-video/1.1">
    <url>
        <loc>
            http://www.site.com/page.html
        </loc>
        <video:video>
            <video:thumbnail_loc>
                http://www.site.com/thumb.jpg
            </video:thumbnail_loc>
            <video:content_loc>http://www.example.com/video123.flv</video:content_loc>
            <video:player_loc allow_embed="yes" autoplay="ap=1">
                http://www.example.com/videoplayer.swf?video=123
            </video:player_loc>
            <video:title>here is the page title</video:title>
            <video:description>and an awesome description</video:description>
            <video:duration>302</video:duration>
            <video:publication_date>2011-02-24T02:03:43+02:00</video:publication_date>
            <video:tag>w00t</video:tag>
            <video:tag>awesome</video:tag>
            <video:tag>omgwtfbbq</video:tag>
            <video:tag>kthxby</video:tag>
        </video:video>
    </url>
</urlset>
Run Code Online (Sandbox Code Playgroud)

我查看了相关的scrapy文档,并编写了以下代码片段,以查看是否做得正确(看来我不^^):

class SitemapSpider(XMLFeedSpider):
    name = "sitemap"
    namespaces = [
        ('', 'http://www.sitemaps.org/schemas/sitemap/0.9'),
        ('video', 'http://www.sitemaps.org/schemas/sitemap-video/1.1'),
    ]
    start_urls = ["http://example.com/sitemap.xml"]
    itertag = 'url'

    def parse_node(self, response, node):
        print "Parsing: %s" % str(node)
Run Code Online (Sandbox Code Playgroud)

但是当我运行蜘蛛时,会出现此错误:

File "/.../python2.7/site-packages/scrapy/utils/iterators.py", line 32, in xmliter
    yield XmlXPathSelector(text=nodetext).select('//' + nodename)[0]
    exceptions.IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

我认为我没有正确定义“默认”名称空间(http://www.sitemaps.org/schemas/sitemap/0.9),但是我找不到如何执行此操作。

遍历url节点然后能够从其子节点提取所需信息的正确方法是什么?


回答:

不幸的是,我无法使用XMLFeedSpider(应该是使用XML解析XML的方法scrapy),但是由于simplebias的回答,我已经找到了一种实现这种“老式方法”的方法。我想出了以下代码(这次有效!):

class SitemapSpider(BaseSpider):
    name = 'sitemap'
    namespaces = {
        'sitemap': 'http://www.sitemaps.org/schemas/sitemap/0.9',
        'video': 'http://www.sitemaps.org/schemas/sitemap-video/1.1',
    }

    def parse(self, response):
        xxs = XmlXPathSelector(response)
        for namespace, schema in self.namespaces.iteritems():
            xxs.register_namespace(namespace, schema)
        for urlnode in xxs.select('//sitemap:url'):
            extract_datas_here()
Run Code Online (Sandbox Code Playgroud)

sam*_*ias 5

Scrapy在后台使用lxml / libxml2,最终调用该node.xpath()方法来执行选择。xpath表达式中任何带有名称空间的元素都必须加上前缀,并且必须传递一个映射来告诉选择器每个前缀都解析为哪个名称空间。

这是一个示例,说明使用该node.xpath()方法时如何将前缀映射到名称空间:

doc = '<root xmlns="chaos"><bar /></root>'
tree = lxml.etree.fromstring(doc)
tree.xpath('//bar')
[]
tree.xpath('//x:bar', namespaces={'x': 'chaos'})
[<Element {chaos}bar at 7fa40f9c50a8>]
Run Code Online (Sandbox Code Playgroud)

在没有使用这个繁琐的XMLFeedSpider类的情况下,我猜测您的名称空间映射和itertag需要遵循相同的方案:

class SitemapSpider(XMLFeedSpider):
    namespaces = [
        ('sm', 'http://www.sitemaps.org/schemas/sitemap/0.9'),
        ]
     itertag = 'sm:url'
Run Code Online (Sandbox Code Playgroud)