So I have a method and when I pass in a straight URL (see code below) the method returns just fine. When I pass in the URL using #{} for the possibility of using different location in Craigslist, it throws the error shown at the bottom. I suppose my question is twofold:

  1. Why doesn't Nokogiri allow me to open this?
  2. Can I change this to accept the URL?

Code:

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")

Error:

 c:\>ruby cljobs.rb C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:35:in
 `initialize': No such file or direct ory -
 sfbay.craigslist.org/sfc/vac/4248712420.html (Errno::ENOENT)
         from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:35:in `open'
         from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:35:in `open'
         from cljobs.rb:7:in `get_post_date'
         from cljobs.rb:40:in `'
有帮助吗?

解决方案

In order to open a URL you need to require OpenURI. Otherwise nokogiri will try to open a file.

require 'open-uri'
listing = Nokogiri::HTML(open(listing_url))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top