2014-05-27 6 views
3

Я пытаюсь использовать scrapy для очистки веб-сайта с несколькими страницами информации.соскабливание нескольких страниц с помощью scrapy

мой код:

from scrapy.spider import BaseSpider 
from scrapy.selector import Selector 
from tcgplayer1.items import Tcgplayer1Item 


class MySpider(BaseSpider): 
    name = "tcg" 
    allowed_domains = ["http://www.tcgplayer.com/"] 
    start_urls = ["http://store.tcgplayer.com/magic/journey-into-nyx?PageNumber=1"] 

    def parse(self, response): 
     hxs = Selector(response) 
     titles = hxs.xpath("//div[@class='magicCard']") 
     for title in titles: 
      item = Tcgplayer1Item() 
      item["cardname"] = title.xpath(".//li[@class='cardName']/a/text()").extract()[0] 

      vendor = title.xpath(".//tr[@class='vendor ']") 
      item["price"] = vendor.xpath("normalize-space(.//td[@class='price']/text())").extract() 
      item["quantity"] = vendor.xpath("normalize-space(.//td[@class='quantity']/text())").extract() 
      item["shipping"] = vendor.xpath("normalize-space(.//span[@class='shippingAmount']/text())").extract() 
      item["condition"] = vendor.xpath("normalize-space(.//td[@class='condition']/a/text())").extract() 
      item["vendors"] = vendor.xpath("normalize-space(.//td[@class='seller']/a/text())").extract() 
      yield item 

Я пытаюсь, чтобы очистить все страницы, пока он не достигнет конца страницы ... иногда будет больше страниц, чем другие, поэтому его трудно точно сказать, где номера страниц заканчиваются.

ответ

9

Идея состоит в том, чтобы увеличивать pageNumber до тех пор, пока не будет найдено titles. Если нет titles на странице - бросить CloseSpider исключение, чтобы остановить паука:

from scrapy.spider import BaseSpider 
from scrapy.selector import Selector 
from scrapy.exceptions import CloseSpider 
from scrapy.http import Request 
from tcgplayer1.items import Tcgplayer1Item 


URL = "http://store.tcgplayer.com/magic/journey-into-nyx?pageNumber=%d" 

class MySpider(BaseSpider): 
    name = "tcg" 
    allowed_domains = ["tcgplayer.com"] 
    start_urls = [URL % 1] 

    def __init__(self): 
     self.page_number = 1 

    def parse(self, response): 
     print self.page_number 
     print "----------" 

     sel = Selector(response) 
     titles = sel.xpath("//div[@class='magicCard']") 
     if not titles: 
      raise CloseSpider('No more pages') 

     for title in titles: 
      item = Tcgplayer1Item() 
      item["cardname"] = title.xpath(".//li[@class='cardName']/a/text()").extract()[0] 

      vendor = title.xpath(".//tr[@class='vendor ']") 
      item["price"] = vendor.xpath("normalize-space(.//td[@class='price']/text())").extract() 
      item["quantity"] = vendor.xpath("normalize-space(.//td[@class='quantity']/text())").extract() 
      item["shipping"] = vendor.xpath("normalize-space(.//span[@class='shippingAmount']/text())").extract() 
      item["condition"] = vendor.xpath("normalize-space(.//td[@class='condition']/a/text())").extract() 
      item["vendors"] = vendor.xpath("normalize-space(.//td[@class='seller']/a/text())").extract() 
      yield item 

     self.page_number += 1 
     yield Request(URL % self.page_number) 

Этот специфический паук бы бросить все 8 страниц данных, а затем остановиться.

Надеюсь, что это поможет.

+0

, который отлично работает ... за помощь! – six7zero9

Смежные вопросы