在浏览使用目录存储文件的基本文件夹系统网站时,
yield scrapy.Request(url1, callback=self.parse)
跟踪链接并抓取已爬网链接的所有内容,但我通常会遇到爬网程序通过根目录链接,并且当根目录进入时,它会获取具有不同URL的所有相同文件之间。
http://example.com/root/sub/file
http://example.com/root/sub/../sub/file
任何帮助都将不胜感激。
这是代码示例的片段
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
答案 0 :(得分:1)
您可以使用os.path.normpath
来规范化所有路径,这样就不会出现重复:
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