没有必要为此使用 Watir。 HTTP HEAD 请求将让您了解 URL 是否解析并且会更快。
Ruby 的Net::HTTP 可以,也可以使用Open::URI。
使用 Open::URI 可以请求一个 URI,然后返回一个页面。因为你并不真正关心页面包含什么,所以你可以扔掉那部分,只返回是否有东西:
require 'open-uri'
if (open('http://www.example.com').read.any?)
puts "is"
else
puts "isn't"
end
好处是 Open::URI 可以解析 HTTP 重定向。缺点是它会返回整页,因此速度会很慢。
Ruby 的 Net::HTTP 可以提供一些帮助,因为它可以使用 HTTP HEAD 请求,它不会返回整个页面,只返回一个标题。这本身不足以知道实际页面是否可访问,因为 HEAD 响应可能会重定向到无法解析的页面,因此您必须遍历重定向,直到您 不 获得重定向,否则您会收到错误消息。 Net::HTTP 文档有一个 example 来帮助您入门:
require 'net/http'
require 'uri'
def fetch(uri_str, limit = 10)
# You should choose better exception.
raise ArgumentError, 'HTTP redirect too deep' if limit == 0
response = Net::HTTP.get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess then response
when Net::HTTPRedirection then fetch(response['location'], limit - 1)
else
response.error!
end
end
print fetch('http://www.ruby-lang.org')
同样,该示例正在返回页面,这可能会减慢您的速度。您可以将get_response 替换为request_head,它会返回类似get_response 的响应,这应该会有所帮助。
在任何一种情况下,您都必须考虑另一件事。许多网站使用“meta refreshes”,这会导致浏览器在解析页面后使用备用 URL 刷新页面。处理这些需要请求页面并对其进行解析,寻找<meta http-equiv="refresh" content="5" /> 标签。
Typhoeus 和 Patron 等其他 HTTP gem 也可以轻松执行 HEAD 请求,因此也可以看看它们。特别是,Typhoeus 可以通过其伙伴Hydra 处理一些繁重的负载,让您轻松使用并行请求。
编辑:
require 'typhoeus'
response = Typhoeus::Request.head("http://www.example.com")
response.code # => 302
case response.code
when (200 .. 299)
#
when (300 .. 399)
headers = Hash[*response.headers.split(/[\r\n]+/).map{ |h| h.split(' ', 2) }.flatten]
puts "Redirected to: #{ headers['Location:'] }"
when (400 .. 499)
#
when (500 .. 599)
#
end
# >> Redirected to: http://www.iana.org/domains/example/
以防万一您还没有玩过,下面是响应的样子。它对您正在查看的那种情况很有用:
(rdb:1) pp response
#<Typhoeus::Response:0x00000100ac3f68
@app_connect_time=0.0,
@body="",
@code=302,
@connect_time=0.055054,
@curl_error_message="No error",
@curl_return_code=0,
@effective_url="http://www.example.com",
@headers=
"HTTP/1.0 302 Found\r\nLocation: http://www.iana.org/domains/example/\r\nServer: BigIP\r\nConnection: Keep-Alive\r\nContent-Length: 0\r\n\r\n",
@http_version=nil,
@mock=false,
@name_lookup_time=0.001436,
@pretransfer_time=0.055058,
@request=
:method => :head,
:url => http://www.example.com,
:headers => {"User-Agent"=>"Typhoeus - http://github.com/dbalatero/typhoeus/tree/master"},
@requested_http_method=nil,
@requested_url=nil,
@start_time=nil,
@start_transfer_time=0.109741,
@status_message=nil,
@time=0.109822>
如果您有很多 URL 需要检查,请查看属于 Typhoeus 的 Hydra example。