【问题标题】:How can I use string interpolation to pass a url into Nokogiri?如何使用字符串插值将 url 传递到 Nokogiri?
【发布时间】:2013-12-18 11:06:02
【问题描述】:

所以我有一个方法,当我传入一个直接的 URL(见下面的代码)时,该方法返回就好了。当我使用 #{} 传递 URL 以在 Craigslist 中使用不同位置的可能性时,它会抛出底部显示的错误。我想我的问题是双重的:

  1. 为什么 Nokogiri 不允许我打开这个?
  2. 我可以更改它以接受 URL 吗?

代码:

def get_post_date(listing_url) 
  # This method takes in a page and returns a date hopefully in a date format
  # but right now text
  listing = Nokogiri::HTML(open(listing_url)).css("p")
  setter = ""
  for element in listing
    if element.css('time').text!=""&&setter==""
      post_time = "poop" # Time.parse(element.css('time').text)
      return "poop"
    end
  end
end

location = "sfbay"
# THIS throws an error
p get_post_date("#{location}.craigslist.org/sfc/vac/4248712420.html")
# THIS works
p get_post_date("sfbay.craigslist.org/sfc/vac/4248712420.html")

错误:

c:\>ruby cljobs.rb C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:35:in `initialize': 没有这样的文件或目录 - sfbay.craigslist.org/sfc/vac/4248712420.html (Errno::ENOENT) 来自 C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:35:in `open' 来自 C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:35:in `open' 来自 cljobs.rb:7:in `get_post_date' 来自 cljobs.rb:40:in `'

【问题讨论】:

    标签: ruby runtime-error nokogiri string-interpolation


    【解决方案1】:

    为了打开一个 URL,你需要 OpenURI。否则 nokogiri 将尝试打开文件。

    require 'open-uri'
    listing = Nokogiri::HTML(open(listing_url))
    

    【讨论】:

    • 我很抱歉......这是在文件中完成的,但我没有将它放在描述中。另外,我需要nokogiri。再一次,如果我传入直接 url(没有 http://),该方法会按预期工作,但如果我使用字符串插值传入,则该方法不起作用。
    • 有趣...好吧,我以为我之前添加了 http://,但也许我没有!它有效
    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多