2014-09-05 45 views
5

我试过这么多的网址正常访问,他们似乎直到我碰到这个特殊的人来罚款:404没有找到,但可以从Web浏览器

require 'rubygems' 
require 'nokogiri' 
require 'open-uri' 

doc = Nokogiri::HTML(open("http://www.moxyst.com/fashion/men-clothing/underwear.html")) 
puts doc 

这是结果:

/Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:353:in `open_http': 404 Not Found (OpenURI::HTTPError) 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:709:in `buffer_open' 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:210:in `block in open_loop' 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:208:in `catch' 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:208:in `open_loop' 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:149:in `open_uri' 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:689:in `open' 
    from /Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:34:in `open' 
    from test.rb:5:in `<main>' 

我可以从网络浏览器访问这个,我只是不明白。

这是怎么回事,我该如何处理这种错误?我可以忽略它,让其余的做他们的工作吗?

+0

您正在使用Ruby 2+,因此没有必要使用'require'rubygems''。这个需求在Ruby 1.9中消失了。 – 2014-09-05 19:02:50

回答

5

你得到404 Not Found (OpenURI::HTTPError),所以,如果你想让你的代码继续下去,救援这个异常。像这样的东西应该工作:

require 'nokogiri' 
require 'open-uri' 

URLS = %w[ 
    http://www.moxyst.com/fashion/men-clothing/underwear.html 
] 

URLs.each do |url| 
    begin 
    doc = Nokogiri::HTML(open(url)) 
    rescue OpenURI::HTTPError => e 
    puts "Can't access #{ url }" 
    puts e.message 
    puts 
    next 
    end 
    puts doc.to_html 
end 

可以使用更通用的例外情况,但后来你遇到了越来越怪异输出问题,或可能在处理导致更多的问题的方式不相关的问题,所以你需要图超出您所需的粒度。

你甚至可以嗅出任何httpd的头,响应的状态,或者查看异常消息,如果你想要更多的控制和想要做的事为401或404

不同我可以从网络浏览器访问这个,我根本就不明白。

那么,这可能是发生在服务器端的事情:也许他们不喜欢你发送的UserAgent字符串? OpenURI documentation显示如何更改该标头:

其他标头字段可由可选的散列参数指定。

open("http://www.ruby-lang.org/en/", 
    "User-Agent" => "Ruby/#{RUBY_VERSION}", 
    "From" => "[email protected]", 
    "Referer" => "http://www.ruby-lang.org/") {|f| 
    # ... 
} 
2

所以发生了什么事情,我该如何处理这种错误。

不知道发生了什么,但可以通过捕获错误来处理它。

begin 
    doc = Nokogiri::HTML(open("http://www.moxyst.com/fashion/men-clothing/underwear.html")) 
    puts doc 
rescue => e 
    puts "I failed: #{e}" 
end 

我可以不理会它,让其余的做好自己的工作?

当然!也许?不确定。我们不知道你的要求。

5

您可能需要 '的User-Agent' 传递作为参数传递给打开方法。有些网站需要一个有效的用户代理,否则他们根本不会回应或显示404未找到错误。

doc = Nokogiri::HTML(open("http://www.moxyst.com/fashion/men-clothing/underwear.html", "User-Agent" => "MyCrawlerName (http://mycrawler-url.com)")) 
+0

这解决了我的问题,谢谢! – daveomcd 2016-11-14 13:10:16

相关问题