如果网站返回“503 service unavailable”错误,则open-uri会抛出异常。例如:
require 'open-uri'
open('http://www.google.co.uk/sorry/?continue=http://www.google.co.uk/search%3Fq%3Dhello%26oq%3Dhello%26ie%3DUTF-8')
# OpenURI::HTTPError: 503 Service Unavailable
# ...
但是,如果您随后在网络浏览器中访问它,它实际上会显示一个带有CAPTCHA而不是错误的页面。
如何确保open-uri不仅仅将此作为例外处理,而是实际处理响应并向我提供页面内容?
答案 0 :(得分:48)
OpenURI::HTTPError
有io
属性,您可以检查以获得所需内容。 io
是一个StringIO
对象,其上定义了多个单例方法(例如status
):
require 'open-uri'
begin
open('http://www.google.co.uk/sorry/?continue=http://www.google.co.uk/search%3Fq%3Dhello%26oq%3Dhello%26ie%3DUTF-8')
rescue OpenURI::HTTPError => error
response = error.io
response.status
# => ["503", "Service Unavailable"]
response.string
# => <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html DIR=\"LTR\">\n<head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"><meta name=\"viewport\" content=\"initial-scale=1\">...
end
但是对于此任务,Net::HTTP
模块可能是更好的选择:
require 'net/http'
response = Net::HTTP.get_response(URI.parse('http://www.google.co.uk/sorry/?continue=http://www.google.co.uk/search%3Fq%3Dhello%26oq%3Dhello%26ie%3DUTF-8'))
response.code
# => "503"
response.body
# => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html DIR=\"LTR\">\n<head><meta http-equiv=\"content-type\" content=\"text/html; ...