2014-02-13 60 views
0

我試圖使用python和Scrapy從Subway UK Restaurant Finder中刮取商店位置數據。我已經設法抓取單個頁面,但是我想設置它來遍歷鏈接末尾的1000個遞歸標識列表。任何幫助,將不勝感激。使用Scrapy刮取遞歸頁面數據

免責聲明:我不知道我在做什麼

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from subway.items import SubwayFinder 

class MySpider(BaseSpider): 
name = "subway" 
allowed_domains = ["http://www.subway.co.uk/"] 
start_urls = ["http://www.subway.co.uk/business/storefinder/store-detail.aspx?id=453056039"] 

def parse(self, response): 
    hxs = HtmlXPathSelector(response) 
    titles = hxs.select("//div[@class='mid']") 
    items = [] 
    for titles in titles: 
     item = SubwayFinder() 
     item ["title"] = titles.select("p/span/text()").extract() 
     items.append(item) 
    return items 

回答

1

在你的代碼所示,一隻蜘蛛函數可以​​返回(或產量)的項目,但它也可以返回/產生Requests,scrapy將項目發送到配置的管道,並調用這些請求以進行進一步的抓取,查看請求字段,回調函數是將用響應調用的函數。

爲了刮掉多個商店位置,您必須查找可鏈接到所有商店的網址格式或索引頁。

例如:

http://www.subway.co.uk/business/storefinder/store-detail.aspx?id=453056039 

看起來並不像一個很好的候選人遍歷所有商店的ID,呼叫453056039個HTTP請求可能不是一個好主意。

我在網站上找不到索引頁面,最接近的可能是將start_urls設置爲'www.subway.co.uk/business/storefinder/search.aspx?pc=' + range(1,10)或其他一些經過驗證的數字,並且進一步檢索每個頁面上的鏈接,還請注意該幸運scrapy不會颳了頁面的兩倍(除非告知),因此出現在多個索引頁面商店詳情頁面是沒有問題的

1

相反的BaseSpider,您可以使用CrawlSpider

看看這個link使用爬網器。

您需要爲scrapy定義rules才能抓取網頁。這些規則將定義您希望scrapy允許抓取的網站和鏈接。

可以對結構檢查這個example對樣品爬行蜘蛛

順便說一句,考慮改變函數名,從文檔:

Warning 

When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses the parse method itself to implement its logic. So if you override the parse method, the crawl spider will no longer work.