Scrapy抓取所有站点地图链接

问题描述 投票:0回答:2

我想抓取固定网站的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
python scrapy web-crawler sitemap
2个回答
2
投票

您需要添加sitemap_rules来处理已爬网网址中的数据,并且您可以根据需要创建任意数量的数据。例如,假设您有一个名为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

0
投票

基本上,您可以创建新的请求对象来抓取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
        return Request(response.url, callback=self.parse_sitemap_url)

    def parse_sitemap_url(self, response):
        # do stuff with your sitemap links
© www.soinside.com 2019 - 2024. All rights reserved.