我知道其他语言中的库可以采用包含本地文件路径或URL的字符串,并将其作为可读IO流打开.
在ruby中有一个简单的方法吗?
单独的SO帖子提供了用于获取Ruby中Web内容的不同方法,但并未完全解释为什么一个方法比另一个方法更受欢迎。
如下所示,使用open()和NET :: HTTP模块来获取Web内容有什么区别?为什么NET :: HTTP被认为是“更好”的方法?
**open() 1:**
require 'open-uri'
file = open('http://hiscore.runescape.com/index_lite.ws?player=zezima')
contents = file.read
**open() 2:**
require 'open-uri'
source = open('http://www.google.com', &:read)
**NET::HTTP 1:**
require 'uri'
require 'net/http'
url = "http://hiscore.runescape.com/index_lite.ws?player=zezima"
r = Net::HTTP.get_response(URI.parse(url).host, URI.parse(url).path)
Run Code Online (Sandbox Code Playgroud) 我刚开始使用TCPSockets.我只想尝试获取谷歌主页.这是我的代码:
require 'socket'
host = 'http://www.google.com'
port = 80
s = TCPSocket.open host, port
s.puts "GET / HTTP/1.1\r\n"
s.puts "Host: Firefox"
s.puts "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
s.puts "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"
s.puts "\r\n"
while line = s.gets
puts line.chop
end
s.close
Run Code Online (Sandbox Code Playgroud)
返回:
HTTP/1.1 302 Document has moved
Location: http://92.242.140.29/?nxdomain=http%3A%2F%2Ffirefox&AddInType=2&PlatformInfo=pbrgen
Run Code Online (Sandbox Code Playgroud)
为什么?我的目标是获取谷歌主页的内容.谢谢