2017-02-27 111 views
0

我花了很多时间试图用scrapy取消信息而没有成功。 我的目标是冲浪通过类别和每个项目废料标题,价格和标题的href链接。Scrapy无法取消物品,xpath无法正常工作

该问题似乎来自parse_items函数。我已经请与firepath XPath和我能够选择的想要的物品,所以也许我只是不抓怎么样的XPath被scrapy处理...

这里是我的代码

from scrapy.contrib.spiders import CrawlSpider, Rule 
from scrapy.linkextractors import LinkExtractor 
from scrapy.selector import Selector 
from ..items import electronic_Item 


class robot_makerSpider(CrawlSpider): 
    name = "robot_makerSpider" 
    allowed_domains = ["robot-maker.com"] 
    start_urls = [ 
     "http://www.robot-maker.com/shop/", 
    ] 

    rules = (

     Rule(LinkExtractor(
      allow=(
       "http://www.robot-maker.com/shop/12-kits-robots", 
       "http://www.robot-maker.com/shop/36-kits-debutants-arduino", 
       "http://www.robot-maker.com/shop/13-cartes-programmables", 
       "http://www.robot-maker.com/shop/14-shields", 
       "http://www.robot-maker.com/shop/15-capteurs", 
       "http://www.robot-maker.com/shop/16-moteurs-et-actionneurs", 
       "http://www.robot-maker.com/shop/17-drivers-d-actionneurs", 
       "http://www.robot-maker.com/shop/18-composants", 
       "http://www.robot-maker.com/shop/20-alimentation", 
       "http://www.robot-maker.com/shop/21-impression-3d", 
       "http://www.robot-maker.com/shop/27-outillage", 
       ), 
      ), 
      callback='parse_items', 
     ), 
    ) 


    def parse_items(self, response): 
     hxs = Selector(response) 
     products = hxs.xpath("//div[@id='center_column']/ul/li") 
     items = [] 

     for product in products: 
      item = electronic_Item() 
      item['title'] = product.xpath(
       "li[1]/div/div/div[2]/h2/a/text()").extract() 
      item['price'] = product.xpath(
       "div/div/div[3]/div/div[1]/span[1]/text()").extract() 
      item['url'] = product.xpath(
       "li[1]/div/div/div[2]/h2/a/@href").extract() 

      #check that all field exist 
      if item['title'] and item['price'] and item['url']: 
       items.append(item) 
     return items 

感谢您的帮助

回答

0

您的蜘蛛xpaths确实有问题。

您的产品的第一个xpath确实有效,但它不够明确,可能很容易失败。虽然产品详细信息xpaths根本不起作用。

我知道了有工作:

products = response.xpath("//div[@class='product-container']") 
items = [] 

for product in products: 
    item = dict() 
    item['title'] = product.xpath('.//h2/a/text()').extract_first('').strip() 
    item['url'] = product.xpath('.//h2/a/@href').extract_first() 
    item['price'] = product.xpath(".//span[contains(@class,'product-price')]/text()").extract_first('').strip() 

所有现代的网站都非常友好解析HTML源(因为他们需要解析它自己为自己看中的CSS样式和JavaScript函数)。

所以一般来说,你应该看看你想使用浏览器检查工具(右键单击 - >检查元素)提取的节点的类和id名称,而不是使用一些自动选择工具。它更可靠,一旦掌握了它就不会花费太多的工作。

+0

谢谢你!我会从这里小心翼翼。您能否向我解释直接从响应中查找xpath而不是使用Selector(response)方法的影响? –

+0

@ArtFilPortraitArtistetisseu它本质上是一回事。 Response对象使用自己创建'Selector',所以你可以有一个方便的'response.selector'快捷方式,而不必每次都创建Selector。 'response.xpath'是'response.selector.xpath'的快捷方式。 [响应来源](https://github.com/scrapy/scrapy/blob/master/scrapy/http/response/text.py#L112)非常简单,你可以自己给它一个高峰:) – Granitosaurus