我想在下载之前测试一个url是否存在 我通常这样做
agent=Mechanize.New
page=agent.get("www.some_url.com/atributes")
但不是我想测试一个页面在下载之前是否归属于该网址
答案 0 :(得分:2)
查看页面是否存在(以及您是否可以通过互联网访问)的唯一方法是执行实际请求。您可以先执行HTTP HEAD请求,该请求仅请求标头,而不是实际内容:
url = "www.some_url.com/atributes"
agent = Mechanize.New
begin
agent.head(url)
page_exists = true
rescue SocketError
page_exists = false
end
if page_exists
page = agent.get(url)
# do something with page ...
end
但话说回来,你可以直接用GET请求摆脱额外的请求并从错误中解救出来:
url = "www.some_url.com/atributes"
agent = Mechanize.New
begin
page = agent.get(url)
# do something with page ...
rescue SocketError
puts "There is no such page."
end