2014-10-31 53 views
3

我試圖scrapy使用scrapy this page。我可以成功地抓取頁面上的數據,但我希望能夠從其他頁面抓取數據。 (接下來說的那些)。繼承人我的代碼的相關部分:使scrapy遞歸地移動到下一頁

def parse(self, response): 
    item = TimemagItem() 
    item['title']= response.xpath('//div[@class="text"]').extract() 
    links = response.xpath('//h3/a').extract() 
    crawledLinks=[] 
    linkPattern = re.compile("^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*@)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+))?$") 

    for link in links: 
     if linkPattern.match(link) and not link in crawledLinks: 
      crawledLinks.append(link) 
     yield Request(link, self.parse) 

    yield item 

我得到正確的信息:從鏈接頁面的標題,但它根本不是「導航」。我如何告訴scrapy導航?

回答

3

看看Scrapy Link Extractors文檔。他們是告訴您的蜘蛛遵循頁面上鍊接的正確方式。

看看你想爬行的頁面,我相信你應該使用2個提取規則。下面是一個簡單的蜘蛛的例子,其規則適合您的TIMES網頁需要:

from scrapy.contrib.spiders import CrawlSpider,Rule 
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor 

class TIMESpider(CrawlSpider): 
    name = "time_spider" 
    allowed_domains = ["time.com"] 
    start_urls = [ 
     'http://search.time.com/results.html?N=45&Ns=p_date_range|1&Ntt=&Nf=p_date_range%7cBTWN+19500101+19500130' 
    ] 

    rules = (
     Rule (SgmlLinkExtractor(restrict_xpaths=('//div[@class="tout"]/h3/a',)) 
      , callback='parse'), 
     Rule (SgmlLinkExtractor(restrict_xpaths=('//a[@title="Next"]',)) 
      , follow= True), 
     ) 

    def parse(self, response): 
     item = TimemagItem() 
     item['title']= response.xpath('.//title/text()').extract() 

     return item 
+0

嗯,那沒用。繼承人我的代碼: – user46257 2014-10-31 20:32:49

+0

嗯,沒有工作。仍然沒有找到鏈接 – user46257 2014-10-31 20:33:38

+0

沒有錯誤,它只是不遵循鏈接。仍然得到我告訴它進行def解析的任何內容。對於我的蜘蛛類,我只是定義了標題,這是我需要的信息。謝謝你的幫助 – user46257 2014-10-31 21:59:25