抓取所有站点地图链接

2024-04-29 20:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想抓取一个固定站点的sitemap.xml中的所有链接。我遇到过Scrapy的sitemapsider。到目前为止,我已经提取了站点地图中的所有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

Tags: 代码url站点网站链接responsenl地图
2条回答

实际上,您可以创建新的请求对象来爬网由sitemapsider创建的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

您需要添加站点地图规则来处理已爬网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

相关问题 更多 >