【发布时间】:2015-07-24 10:15:19
【问题描述】:
我正在尝试从 Wikipedia 下载一个页面。对于这样的任务,我正在使用宝石。当使用 net/http 时,我得到的只是一个空字符串。所以我尝试了 open-uri 并且效果很好。
不过,我更喜欢第一个选项,因为它给了我更明确的控制;但为什么它返回一个空字符串?
class Downloader
attr_accessor :entry, :url, :page
def initialize
# require 'net/http'
require 'open-uri'
end
def getEntry
print "Article name? "
@entry = gets.chomp
end
def getURL(entry)
if entry.include?(" ")
@url = "http://en.wikipedia.org/wiki/" + entry.gsub!(/\s/, "_")
else
@url = "http://en.wikipedia.org/wiki/" + entry
end
@url.downcase!
end
def getPage(url)
=begin THIS FAULTY SOLUTION RETURNS AN EMPTY STRING ???
connector = URI.parse(url)
connection = Net::HTTP.start(connector.host, connector.port) do |http|
http.get(connector.path)
end
puts "Body:"
@page = connection.body
=end
@page = open(url).read
end
end
test = Downloader.new
test.getEntry
test.getURL(test.entry)
test.getPage(test.url)
puts test.page
P.S.:我是一名自学成才的程序员,所以代码可能不适合好的做法。我很抱歉。
【问题讨论】:
-
不知道,我得到了正确的身体。 (顺便说一句,您不必检查
entry是否包含空格;gsub很乐意将零空格更改为零下划线。您不应该在参数上使用gsub!,除非它是该方法的目的 -意想不到的后果等等。不要在initialize中要求,除非您有特殊理由,否则文件顶部通常更清晰。)
标签: ruby-on-rails ruby net-http open-uri