2017-07-20 1 views
-1

Ich habe derzeit eine Scraper-Datei namens scraper.rb. Ich muss herausfinden, wie man die Ausgabe von diesem nimmt und es auf einem Sinatra-Server anzeigen lässt. Wenn Sie auch eine Erklärung liefern könnten, warum Ihre Antwort funktioniert, wäre das großartig, vielen Dank im Voraus.Erstellen Sie einen Sinatra-Server, der die aktuellen Job-Postings anzeigt, wenn ich den Root-Pfad des Servers besuche

require 'httparty' 
require 'nokogiri' 


url = "https://miami.craigslist.org/search/sof" 


response = HTTParty.get url 

puts response.body 
puts response.headers['content-type'] 


dom = Nokogiri::HTML(response.body) 

num = 0 

dom.css("a.hdrlnk").each do |job| 
num +=1 
print "#{num} " 
puts job.content 
puts job['href'] 
end 
+0

Es gibt so viele Lösungen für Ihr Problem, Sie können nur eine Zwischenspeichervariable verwenden und Ihre Ergebnisse dort speichern, Sie können sie in Dateien oder in einer echten SQL/noSQL-Datenbank speichern. –

Antwort

0

Ich weiß nicht die Struktur Ihrer App, folgende funktioniert für mich. Hoffe es hilft dir.

require 'sinatra' 

get '/' do 
    @data = get_craig_data 
    erb :index 
end 


private 
    def get_craig_data 
    require 'httparty' 
    require 'nokogiri' 

    url = "https://miami.craigslist.org/search/sof" 
    data = [] # array to be returned 
    response = HTTParty.get url 
    dom = Nokogiri::HTML(response.body) 
    num = 0A little more detail would 
    dom.css("a.hdrlnk").each do |job| 
     num +=1 
     data.push({num: "#{num}", content: job.content, link: job['href']}) 
    end 
    data 
    end#method end 
__END__ 


@@index 
    <table> 
    <thead> 
    <tr> 
     <th>Num#</th><th>Job Content</th><th>Link</th> 
    </tr> 
    </thead> 
    <tbody> 
    <%@data.count.times do |i|%> 
     <tr> 
     <td><%[email protected][i][:num]%></td> 
     <td><%[email protected][i][:content]%></td> 
     <td><%[email protected][i][:link]%></td> 
     </tr> 
    <%end%> 
    </tbody> 
    </table> 
require 'sinatra' 

get '/' do 
    @data = get_craig_data 
    erb :index 
end 


private 
    def get_craig_data 
    require 'httparty' 
    require 'nokogiri' 

    url = "https://miami.craigslist.org/search/sof" 
    data = [] # array to be returned 
    response = HTTParty.get url 
    dom = Nokogiri::HTML(response.body) 
    num = 0A little more detail would 
    dom.css("a.hdrlnk").each do |job| 
     num +=1 
     data.push({num: "#{num}", content: job.content, link: job['href']}) 
    end 
    data 
    end#method end 
__END__ 


@@index 
    <table> 
    <thead> 
    <tr> 
     <th>Num#</th><th>Job Content</th><th>Link</th> 
    </tr> 
    </thead> 
    <tbody> 
    <%@data.count.times do |i|%> 
     <tr> 
     <td><%[email protected][i][:num]%></td> 
     <td><%[email protected][i][:content]%></td> 
     <td><%[email protected][i][:link]%></td> 
     </tr> 
    <%end%> 
    </tbody> 
    </table> 
Verwandte Themen