2014-12-09 4 views
0

스크립트는 finance.yahoo.com에서 역사적인 주가를 다운로드합니다. 시세의 배열은 스크립트를 반복하는 데 사용되며 시세 배열에 따라 li'nks를 만들고 각 시세와 관련된 데이터를 다운로드합니다. 그러나 시세 기호 중 일부는 더 이상 최신 정보가 아니므로 yahoo는 가격 정보가 포함 된 csv 대신 404 페이지를 제공합니다. 오류 페이지는 대신 csv에 저장되고 내 컴퓨터에 저장됩니다. 이 파일을 다운로드하지 않으려면 '죄송합니다, 요청한 페이지를 찾을 수 없습니다.'라는 문자열을 찾고 있는데, 404 페이지의 표시기로 각 yahoos 오류 사이트에 포함되어 있습니다. 코드의오류가없는 경우에만 주가 데이터를 다운로드하는 방법 (404)?

행동 (출력 코드 아래 참조)

코드 실행을 모두 시세 및 다운로드 모든 주가를 .csv의를 통해. 이것은 모든 증권 시세에 잘 작동하지만, 일부 시세 표시는 야후에 의해 더 이상 사용되지 않습니다. 더 이상 사용되지 않는 티커 심볼의 경우 yahoos 404 페이지가 포함 된 .csv 파일을 다운로드합니다. 모든 파일 (실제 데이터가 들어있는 파일)은 c : \ Users \ W7ADM \ stock-price-leecher \ data2 디렉토리에 다운로드됩니다.

문제 :

코드가 csv 파일로 404 페이지를 다운로드, 그러나 다만이 경우에는 아무것도하지 않고 루프의 다음 종목 기호로 이동할 수 있도록 싶습니다. 나는 "죄송합니다. 요청한 페이지를 찾을 수 없습니다."라는 문자열을 찾는 if-condition을 사용하여 이것을 수행하려고합니다. yahoos 404 페이지에서 디플레이션됩니다. 결국 나는 실제로 존재하는 시세 표시기에 대한 모든 csv를 다운로드하고 내 hdd에 저장하기를 바라고 있습니다.

var url_begin = 'http://real-chart.finance.yahoo.com/table.csv?s='; 
var url_end = '&a=00&b=1&c=1950&d=11&e=31&f=2050&g=d&ignore=.csv'; 
var tickers = []; 
var link_created = ''; 

var casper = require('casper').create({ 
    pageSettings: { 
     webSecurityEnabled: false 
    } 
});     

casper.start('http://www.google.de', function() {    
     tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is retrievable, 0AM.DE is not 
     //loop through all ticker symbols 
     for (var i in tickers){ 
       //create a link with the current ticker 
       link_created=url_begin + tickers[i] + url_end; 
       //check to see, if the created link returns a 404 page 
       this.open(link_created); 
       var content = this.getHTML(); 
       //If is is a 404 page, jump to the next iteration of the for loop 
       if (content.indexOf('Sorry, the page you requested was not found.')>-1){ 
         console.log('No Page found.'); 
         continue; //At this point I want to jump to the next iteration of the loop. 
       } 
       //Otherwise download file to local hdd 
       else { 
         console.log(link_created); 
         this.download(link_created, 'stock-price-leecher\\data2\\'+tickers[i]+'.csv'); 
       } 
     } 
}); 

casper.run(function() { 
     this.echo('Ende...').exit(); 
}); 

아웃풋 :

C:\Users\Win7ADM>casperjs spl_old.js 
ADS.DE,0AM.DE 
http://real-chart.finance.yahoo.com/table.csv?s=ADS.DE&a=00&b=1&c=1950&d=11&e=31 
&f=2050&g=d&ignore=.csv 
http://real-chart.finance.yahoo.com/table.csv?s=0AM.DE&a=00&b=1&c=1950&d=11&e=31 
&f=2050&g=d&ignore=.csv 
Ende... 

C:\Users\Win7ADM> 

답변

0

casper.open 비동기 (비 차단),하지만 당신은 차단 방식을 사용합니다. 페이지가로드 될 때 호출되는 콜백이있는 casper.thenOpen을 사용해야하며이를 처리 할 수 ​​있습니다.

casper.start("http://example.com"); 

tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is still retrievable, 0AM.DE is not 
tickers.forEach(function(ticker){ 
    var link_created = url_begin + ticker + url_end; 
    casper.thenOpen(link_created, function(){ 
     console.log("open", link_created); 
     var content = this.getHTML(); 
     if (content.indexOf('Sorry, the page you requested was not found.') > -1) { 
      console.log('No Page found.'); 
     } else { 
      console.log("downloading..."); 
      this.download(link_created, 'test14_'+ticker+'.csv'); 
     } 
    }); 
}); 

casper.run(); 

대신 thenOpen 콜백을 사용하여, 당신은 또한 page.resource.received 이벤트에 등록 할 수 있습니다 및 상태를 확인하여 구체적으로 다운로드합니다. 하지만 이제는 ticker에 액세스 할 수 없으므로 전역 변수에 저장하거나 resource.url에서 구문 분석해야합니다.

var i = 0; 
casper.on("page.resource.received", function(resource){ 
    if (resource.stage === "end" && resource.status === 200) { 
     this.download(resource.url, 'test14_'+(i++)+'.csv'); 
    } 
}); 

casper.start("http://example.com"); 

tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is still retrievable, 0AM.DE is not 
tickers.forEach(function(ticker){ 
    var link_created = url_begin + ticker + url_end; 
    casper.thenOpen(link_created); 
}); 

casper.run(); 

난 당신이 open 또는 thenOpen이 작업을 수행해야한다고 생각하지 않습니다. PhantomJS에서는 작동하지만 SlimerJS에서는 작동하지 않을 수 있습니다.


실제로 다운로드를 시도했는데 페이지가 이상하지 않아 다운로드가 실패합니다. example.com과 같은 더미 페이지를로드하고 __utils__.sendAJAX (페이지 컨텍스트에서만 액세스 가능) 및 write fs 모듈을 사용하여 직접 CSV 파일을 다운로드 할 수 있습니다. 확인한 특정 404 오류 페이지 텍스트를 기반으로 작성해야합니다.

casper.start("http://example.com"); 

casper.then(function(){ 
    tickers = ['ADS.DE', '0AM.DE']; //ADS.DE is still retrievable, 0AM.DE is not 
    tickers.forEach(function(ticker){ 
     var link_created = url_begin + ticker + url_end; 
     var content = casper.evaluate(function(url){ 
      return __utils__.sendAJAX(url, "GET"); 
     }, link_created); 
     console.log("len: ", content.length); 
     if (content.indexOf('Sorry, the page you requested was not found.') > -1) { 
      console.log('No Page found.'); 
     } else { 
      console.log("writing..."); 
      fs.write('test14_'+ticker+'.csv', content); 
     } 
    }); 
}); 

casper.run();