【问题标题】:Build a Sinatra server that displays the current job postings when I visit that server’s root path构建一个 Sinatra 服务器,当我访问该服务器的根路径时显示当前的招聘信息
【发布时间】:2017-07-25 15:10:11
【问题描述】:

我目前有一个名为 scraper.rb 的刮板文件。我需要弄清楚如何从中获取输出并将其显示在 Sinatra 服务器上。如果您还可以解释为什么您的答案有效,那就太好了,在此先感谢。

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

【问题讨论】:

  • 您的问题有很多解决方案,您可以只使用缓存变量并将结果保存在那里,您可以将其保存在文件中或真正的 SQL/noSQL 数据库中。

标签: ruby sinatra scraper


【解决方案1】:

我不知道您的应用程序的结构,以下对我有用。希望对你有帮助。

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><%=@data[i][:num]%></td>
        <td><%=@data[i][:content]%></td>
        <td><%=@data[i][:link]%></td>
      </tr>
    <%end%>
    </tbody>
  </table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多