2017-02-27 89 views
0

我正在学习scrapy,因为某些原因它只返回页面上的第一项。有人能告诉我我做错了什么吗?scrapy返回第一项

下面是我的代码:

class RuvillaSpider(Spider): 

    name = "RuvillaSpider" 
    allowded_domains = ["ruvilla.com"] 
    start_urls = ["https://www.ruvilla.com/men/footwear.html?dir=desc&limit=45&order=news_from_date"] 

    def parse(self, response): 
     products = Selector(response).xpath('//div[@class="category-products"]') 

     if not products: 
      raise CloseSpider('RuvillaSpider: DONE, NO MORE PAGES.') 

     for product in products: 
      item = RuvillaItem() 
      item['name'] = product.xpath('ul/li/div/div[1]/a/@title').extract()[0] 
      item['link'] = product.xpath('ul/li/div/div[1]/a/@href').extract()[0] 
      item['image'] = product.xpath('ul/li/div/div[1]/a/img/@src').extract()[0] 
      yield item 
+0

这里,除了定义你的类,你是*先验*没有任何错误。你对这个类的实例做什么也可能是有帮助的。例如,这可能会告诉我们您意识到您正在使用发电机。 – Kanak

回答

0

你的XPath似乎只返回1个产品为products变量。

尝试:

$ scrapy shell "https://www.ruvilla.com/men/footwear.html?dir=desc&limit=45&order=news_from_date" 
In[1]: response.xpath('//div[@class="category-products"]') 
Out[1]: [<Selector xpath='//div[@class="category-products"]' data=u'<div class="category-products">\n<div cla'>] 

如此看来你的XPath是不是每一个人项目,但对于容器中的物品都在为了解决这个问题,你需要生成一个选择每产品容器而不是一个XPath :

def parse(self, response): 
    products = Selector(response).xpath('//div[@class="category-products"]//li[contains(@class,"item")]') 

    for product in products: 
     item = dict() 
     item['name'] = product.xpath('.//a/@title').extract_first() 
     item['link'] = product.xpath('.//a/@href').extract_first() 
     item['image'] = product.xpath('.//a/img/@src').extract_first() 
     yield item 
    next_page = response.xpath("//li[@class='current']/following-sibling::li[1]/a/@href").extract_first() 
    if next_page: 
     yield Request(next_page) 
0

你的xpath是错误的。

使用此XPath:

( '// DIV [@类= “类产品”]/UL /李')