如何使用字符串插值将url传递到Nokogiri



所以我有一个方法,当我传入一个直接的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(错误号::ENOENT)来自C/Ruby193/lib/rube/1.9.1/open-uri.rb:35:在"open"中来自C/Ruby193/lib/rube/1.9.1/open-uri.rb:35:在"open"中来自cljobs.rb:7:在"get_post_date"中来自cljobs.rb:40:in">

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

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

最新更新