1

While scraping through a Basic Folder System Website that uses Directories to store file,

yield scrapy.Request(url1, callback=self.parse)

follows the links and scrapes all the content of the crawled link, but I'm usually encountered with the crawler passing through a Root Directory link and it gets all the same files with the different url as the root directory comes in between.

http://example.com/root/sub/file
http://example.com/root/sub/../sub/file

Any help would be appreciated.

Here's a snippet for the code sample

class fileSpider(Spider):
    name = 'filespider'
    def __init__(self, filename=None):
        if filename:
            with open(filename, 'r') as f:
                self.start_urls =  [url.strip() for url in f.readlines()]

    def parse(self, response):
        item = Item()
        for url in response.xpath('//a/@href').extract():
            url1 = response.url + url
            if(url1[-4::] in videoext):
                item['name'] = url
                item['url'] = url1
                item['depth'] = response.meta["depth"]
                yield item
            elif(url1[-1]=='/'):
                yield scrapy.Request(url1, callback=self.parse)   
        pass

1 Answers1

1

you can use os.path.normpath to normalize all the paths, so you don't get duplicates:

import os
import urlparse
...

    def parse(self, response):
        item = Item()
        for url in response.xpath('//a/@href').extract():
            url1 = response.url + url

            # =======================
            url_parts = list(urlparse.urlparse(url1))
            url_parts[2] = os.path.normpath(url_parts[2])
            url1 = urlparse.urlunparse(url_parts)
            # =======================

            if(url1[-4::] in videoext):
                item['name'] = url
                item['url'] = url1
                item['depth'] = response.meta["depth"]
                yield item
            elif(url1[-1]=='/'):
                yield scrapy.Request(url1, callback=self.parse)   
        pass
eLRuLL
  • 18,488
  • 9
  • 73
  • 99