2016-07-27 6 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을 것이다. 로그와 통계에주의를 기울여야합니다. 특히 무언가 잘못되었을 때 알 수 있습니다.