我知道mechanize有post_connect_hooks
,它将在检索页面后运行。但是,如果发生异常,例如,如果您请求像"http://dsjkhbgdfb.comsfg"
这样的未知URL,则它将运行pre_connect_hooks
,而不是post_connect_hooks
。有什么方法可以确保post_connect_hooks
(或类似的东西(始终运行吗?
agent = Mechanize.new
agent.pre_connect_hooks << lambda do |request_agent, request|
puts "increment a counter"
end
agent.post_connect_hooks << lambda do |request_agent, uri, response, response_body|
puts "decrement a counter"
end
agent.get("http://dsjkhbgdfb.comsfg")
#=> increment a counter
#=> SocketError: getaddrinfo: nodename nor servname provided, or not known
正如您所看到的,"递减计数器"没有运行,因为以前发生过错误。
尝试此操作,因为它可能只是强制执行并忽略错误
try:
agent.get("http://dsjkhbgdfb.comsfg")
except socket.error:
pass # Basically, ignore the error