如何使用Ruby HTTP :: Net处理404错误? [英] How to handle 404 errors with Ruby HTTP::Net?

查看:71
本文介绍了如何使用Ruby HTTP :: Net处理404错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析网页,但有时会出现404错误。这是我用来获取网页的代码:

I'm trying to parse web pages but I sometimes get 404 errors. Here's the code I use to get the web page:

result = Net::HTTP::get URI.parse(URI.escape(url))

如何测试结果是一个404错误代码?

How do I test if result is a 404 error code?

推荐答案

重写你的代码如下:

uri = URI.parse(url)
result = Net::HTTP.start(uri.host, uri.port) { |http| http.get(uri.path) }
puts result.code
puts result.body

这将打印身体后面的状态代码。

That will print the status code followed by the body.

这篇关于如何使用Ruby HTTP :: Net处理404错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆