[英]Recursive web crawling with Scrapy
我開始用Python編程。 作為我的第一個項目,我想使用Scrapy-Python模塊創建網絡搜尋器。 我遇到了兩天以來一直在苦苦掙扎的問題,找不到解決方案。 任何幫助,將不勝感激。
我想從Allegro-波蘭eBay上抓取並刪除有關汽車價格的數據。 我的項目的第一階段是下載汽車品牌列表以及子類別(我想盡可能深入地研究子類別)和要約數量。
我從以下站點開始爬網: http : //allegro.pl/osobowe-pozostale-4058 ,可在其中單擊左側面板上的類別。 到目前為止,我只關注左側面板中的數據。
結果,我想接收具有以下結構的json文件:
{
{"name": "BMW" # name
"url": "http://allegro.pl/osobowe-bmw-4032" # link to subcategories
"count": 12726 # numbers of offer
"subcategories":[
{ "name": "Seria 1" # name
"url": "http://allegro.pl/bmw-seria-1-12435" # link to subcategories
“count": 832 # numbers of offer
}
,
{another BMW model}
,
…
]
}
,
{another car brand }
,
…
}
由於某些品牌沒有子類別,而有些品牌卻有子類別的子類別,因此Web clawler必須非常靈活。 有時應該停在主頁上,有時更深一些,停在死胡同的子類別中。
BMV ->Seria 1 -> E87 (2004-2013) vs Acura (only 2 offers and no subcategories)
到目前為止,我已經能夠創建第一個蜘蛛,看起來像這樣
Items.py
import scrapy
class Allegro3Item(scrapy.Item):
name=scrapy.Field()
count=scrapy.Field()
url = scrapy.Field()
subcategory= scrapy.Field()
蜘蛛:
import scrapy
from allegro3.items import Allegro3Item
linki=[]
class AlegroSpider(scrapy.Spider):
name = "AlegroSpider"
allowed_domains = ["allegro.pl"]
start_urls = ["http://allegro.pl/samochody-osobowe-4029"]
def parse(self, response):
global linki
if response.url not in linki:
linki.append(response.url)
for de in response.xpath('//*[@id="sidebar-categories"]/div/nav/ul/li'):
la = Allegro3Item()
link = de.xpath('a/@href').extract()
la['name'] = de.xpath('a/span/span/text()').extract()[0].encode('utf-8')
la['count'] = de.xpath('span/text()').extract()[0].encode('utf-8')
la['url'] = response.urljoin(link[0]).encode('utf-8')
la['subcategory']=[]
if la['url'] is not None:
if la['url'] not in linki:
linki.append(la['url'])
request = scrapy.Request(la['url'],callback=self.SearchFurther)
#la['subcategory'].append(request.meta['la2'])
yield la
def SearchFurther(self,response):
global linki
for de in response.xpath('//*[@id="sidebar-categories"]/div/nav/ul/li'):
link = de.xpath('a/@href').extract()
la2 = Allegro3Item()
la2['name'] = de.xpath('a/span/span/text()').extract()[0].encode('utf-8')
la2['count'] = de.xpath('span/text()').extract()[0].encode('utf-8')
la2['url'] = response.urljoin(link[0]).encode('utf-8')
yield la2
在這段代碼中,我嘗試使用以下方法創建類/項目:
我在使用4時遇到問題。創建附加請求“ SearchFurther”時。
request = scrapy.Request(la['url'],callback=self.SearchFurther)
我不知道如何將SearchFurther結果的la2項傳遞給先前的請求,因此我可以將la2附加到la [subcategory]作為列表的其他元素(一個品牌可以具有許多子類別)。
我將不勝感激。
請查看以下文檔: http : //doc.scrapy.org/en/latest/topics/request-response.html#passing-additional-data-to-callback-functions
在某些情況下,您可能希望將參數傳遞給這些回調函數,以便稍后可以在第二個回調中接收參數。 您可以為此使用Request.meta屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.