使用Ruby获取网页内容 - 我遇到了麻烦

And*_*rew 12 ruby

我想从这个*页面中删除内容.我查找的所有内容都提供了解析CSS元素的解决方案; 但是,那个页面没有.

这是我发现的唯一代码应该有效的代码:

file = File.open('http://hiscore.runescape.com/index_lite.ws?player=zezima', "r")
contents = file.read
puts contents
Run Code Online (Sandbox Code Playgroud)

错误:

tracker.rb:1:in 'initialize': Invalid argument - http://hiscore.runescape.com/index_lite.ws?player=zezima (Errno::EINVAL)
  from tracker.rb:1:in 'open'
  from tracker.rb:1
Run Code Online (Sandbox Code Playgroud)

*http://hiscore.runescape.com/index_lite.ws?player=zezima

如果您尝试将其格式化为帖子中的链接,则由于某种原因它无法识别URL中的下划线(_).

Cod*_*lan 39

你真的想使用Kernel类提供的open(),它可以从你需要首先需要OpenURI库的URI中读取:

require 'open-uri'
Run Code Online (Sandbox Code Playgroud)

像这样使用:

require 'open-uri'
file = open('http://hiscore.runescape.com/index_lite.ws?player=zezima')
contents = file.read
puts contents
Run Code Online (Sandbox Code Playgroud)

这个相关的SO线程涵盖了同样的问题:

从本地文件或URL打开IO流


hal*_*dan 7

获取网站内容的适当方法是通过Ruby中的NET :: HTTP模块:

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)

File.open()不支持URI.

祝愿,
费边


YOU*_*YOU 6

请使用open-uri,它支持uri和本地文件

require 'open-uri'
contents  = open('http://www.google.com') {|f| f.read }
Run Code Online (Sandbox Code Playgroud)