2013-08-13 3 views
1

APOD (오늘의 천문 사진)에서 데이터를 긁는 루비 씨앗 파일을 사용하고 있습니다. 수천 개의 항목이 있으므로 지난 365 개의 이미지를 가져 오기 위해 긁힌 자국을 제한 할 수있는 방법이 있습니까?데이터 스크랩 검색 한도

require 'rubygems' 
require 'open-uri' 
require 'open-uri' 
require 'nokogiri' 
require 'curl' 
require 'fileutils' 

BASE = 'http://antwrp.gsfc.nasa.gov/apod/' 
FileUtils.mkdir('small') unless File.exist?('small') 
FileUtils.mkdir('big') unless File.exist?('big') 

f = open 'http://antwrp.gsfc.nasa.gov/apod/archivepix.html' 
html_doc = Nokogiri::HTML(f.read) 
html_doc.xpath('//b//a').each do |element| 
    imgurl = BASE + element.attributes['href'].value 
    doc = Nokogiri::HTML(open(imgurl).read) 
    doc.xpath('//p//a//img').each do |elem| 
     small_img = BASE + elem.attributes['src'].value 
     big_img = BASE + elem.parent.attributes['href'].value 
     s_img_f = open("small/#{File.basename(small_img)}", 'wb') 
     b_img_f = open("big/#{File.basename(big_img)}", 'wb') 
     rs_img = Curl::Easy.new(small_img) 
     rb_img = Curl::Easy.new(big_img) 
     rs_img.perform 
     s_img_f.write(rs_img.body_str) 
     rb_img.perform 
     b_img_f.write(rb_img.body_str) 
     s_img_f.close 
     puts "Download #{File.basename(small_img)} finished." 
     b_img_f.close 
     puts "Download #{File.basename(big_img)} finished." 
     rs_img.close 
     rb_img.close 
    end 
end 
puts "All done." 
+0

을 왜 OpenURI 두 번이 필요합니까? 그렇게하면 더 빨리 진행되지 않습니다. –

+0

질문을 게시 할 때 우연히 두 줄을 복사했습니다. – Reuben

답변

1

당신은 특정 인덱스 사이의 요소를 얻기 위해 배열과 같은 설정 노드를 처리 할 수 ​​있습니다 :

여기 내가 사용하고 종자 코드입니다.

링크의 노드 집합에 [0..364]을 추가

html_doc.xpath('//b//a')[0..364].each do |element| 
+0

'0..365'는 366 개의 요소입니다. –

+0

고맙습니다 @ theTinMan. 코드가 업데이트되었습니다. –