Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 用nethttp解析html页面_Ruby - Fatal编程技术网

Ruby 用nethttp解析html页面

Ruby 用nethttp解析html页面,ruby,Ruby,在前面的一个问题中,我找到了一个答案,它是一种被黑客攻击但仍在工作的方法,可以使用 url = %x(curl http://google.com) simian = curl.match(/<title>(.*)<\/title>/)[1] puts simian url=%x(curl)http://google.com) simian=curl.match(/(.*)/)[1] 猿猴 现在我想知道是否有更好的方法,使用诸如net/http之类的ruby标准

在前面的一个问题中,我找到了一个答案,它是一种被黑客攻击但仍在工作的方法,可以使用

 url = %x(curl http://google.com)
 simian = curl.match(/<title>(.*)<\/title>/)[1]
 puts simian
url=%x(curl)http://google.com)
simian=curl.match(/(.*)/)[1]
猿猴
现在我想知道是否有更好的方法,使用诸如net/http之类的ruby标准库来获取url(代替curl)

另一个问题是,如果页面标题中有一些非标准字符,则不会对其进行解析,并且无法完成curl.match。我试过了

 simian = s.encode('UTF-8') and then
 simian = curl.match(/<title>(.*)<\/title>/)[1]
simian=s.encode('UTF-8'),然后
simian=curl.match(/(.*)/)[1]
但它显示了像1#这样的奇怪角色
提前感谢您的帮助

使用nokogiri可能是最简单的解决方案:

require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('http://www.google.com'))
elt = doc.xpath('//title').first
puts elt.text() if !elt.nil?

使用nokogiri可能是最简单的解决方案:

require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('http://www.google.com'))
elt = doc.xpath('//title').first
puts elt.text() if !elt.nil?

嗨,Sebastien,这是真的,它可以工作,但即使是Nokogiri在这种情况下也失败了doc=Nokogiri::HTML(open('))nokotest2.rb:5:in
':nil:NilClass(NoMethodError)的未定义方法
text:)如果您试图访问的页面没有标题,那么
xpath
查询将返回nil,因此出现了错误。我编辑后添加了一个零检查,如果没有标题,这几乎是你能做的最好的了!;)嗨,Sebastien,这是真的,它可以工作,但即使是Nokogiri在这种情况下也失败了doc=Nokogiri::HTML(open('))nokotest2.rb:5:in
':nil:NilClass(NoMethodError)的未定义方法
text:)如果您试图访问的页面没有标题,那么
xpath
查询将返回nil,因此出现了错误。我编辑后添加了一个零检查,如果没有标题,这几乎是你能做的最好的了!;)