2016-07-27 2 views
0

URL構造がわからないサイトでScrapyを使用しようとしています。条件付きURLをScrapでスクラブする

私はしたいと思います:のXpathを含むページから

  • のみ抽出データ "// divの[@クラス=" 製品ビュー "]"。

  • エキス(CSV)で印刷URL、名前や価格のXPath

私は以下のスクリプトを実行すると、私が得るすべてはURLの

scrapy crawl dmoz>test.txt

のランダムなリストであります
from scrapy.selector import HtmlXPathSelector 
from scrapy.spider import BaseSpider 
from scrapy.http import Request 

DOMAIN = 'site.com' 
URL = 'http://%s' % DOMAIN 

class MySpider(BaseSpider): 
    name = "dmoz" 
    allowed_domains = [DOMAIN] 
    start_urls = [ 
     URL 
    ] 

    def parse(self, response): 
     for url in response.xpath('//a/@href').extract(): 
      if not (url.startswith('http://') or url.startswith('https://')): 
       url= URL + url 
      if response.xpath('//div[@class="product-view"]'): 
       url = response.extract() 
       name = response.xpath('//div[@class="product-name"]/h1/text()').extract() 
       price = response.xpath('//span[@class="product_price_details"]/text()').extract() 
      yield Request(url, callback=self.parse) 
      print url 

答えて

1

あなたが探しているのはscrapy.spiders.Crawlspiderです。

しかし、ほとんどあなた自身のアプローチでそれを得ました。ここには固定バージョンがあります。

from scrapy.linkextractors import LinkExtractor 
def parse(self, response): 
    # parse this page 
    if response.xpath('//div[@class="product-view"]'): 
     item = dict() 
     item['url'] = response.url 
     item['name'] = response.xpath('//div[@class="product-name"]/h1/text()').extract_first() 
     item['price'] = response.xpath('//span[@class="product_price_details"]/text()').extract_first() 
     yield item # return an item with your data 
    # other pages 
    le = LinkExtractor() # linkextractor is smarter than xpath '//a/@href' 
    for link in le.extract_links(response): 
     yield Request(link.url) # default callback is already self.parse 

今、あなたは、単にあなたのアイテムのscrapy crawl myspider -o results.csvとscrapy意志出力CSVファイルを実行することができます。ログと統計情報に目を留めておくが、何かが間違っているかどうかを知る方法だ。