gpt4 book ai didi

ruby - 使用 ruby​​ mechanize 捕获超时错误

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:03 25 4
gpt4 key购买 nike

我有一个 Mechanize 功能可以让我退出网站,但在极少数情况下它会让我超时。该功能涉及转到特定页面,然后单击注销按钮。有时,当进入注销页面或单击注销按钮时,mechanize 会遇到超时,代码会崩溃。所以我做了一个小的救援,它似乎在第一段代码下面看到的那样工作。

def logmeout(agent)
page = agent.get('http://www.example.com/')
agent.click(page.link_with(:text => /Log Out/i))
end

通过救援注销:

def logmeout(agent)
begin
page = agent.get('http://www.example.com/')
agent.click(page.link_with(:text => /Log Out/i))
rescue Timeout::Error
puts "Timeout!"
retry
end
end

假设我正确理解 rescue,即使只是点击超时,它也会重新执行这两个操作,所以为了提高效率,我想知道我是否可以在这种情况下使用 proc 并向它传递一个代码块。这样的事情会有效吗:

def trythreetimes
tries = 0
begin
yield
rescue
tries += 1
puts "Trying again!"
retry if tries <= 3
end
end

def logmeout(agent)
trythreetimes {page = agent.get('http://www.example.com/')}
trythreetimes {agent.click(page.link_with(:text => /Log Out/i))}
end

请注意,在我的 trythreetimes 函数中,我将其保留为通用 rescue,因此该函数将更易于重用。

非常感谢任何人可以提供的任何帮助,我意识到这里有几个不同的问题,但它们都是我想要学习的东西!

最佳答案

我认为您最好设置 Mechanize::HTTP::Agent::read_timeout,而不是对某些 Mechanize 请求重试超时。归因于合理的秒数,例如 2 或 5,无论如何可以防止此请求的超时错误。

那么,您的注销过程似乎只需要访问一个简单的 HTTP GET 请求。我的意思是没有要填写的表格,所以没有 HTTP POST 请求。因此,如果我是你,我会更喜欢检查页面源代码(使用 Firefox 或 Chrome 时按 Ctrl+U),以确定你的 agent.click(page.link_with(:text =>/注销/i))它应该更快,因为这些类型的页面通常是空白的,Mechanize 不必在内存中加载完整的 html 网页。

这是我更喜欢使用的代码:

def logmeout(agent)
begin
agent.read_timeout=2 #set the agent time out
page = agent.get('http://www.example.com/logout_url.php')
agent.history.pop() #delete this request in the history
rescue Timeout::Error
puts "Timeout!"
puts "read_timeout attribute is set to #{agent.read_timeout}s" if !agent.read_timeout.nil?
#retry #retry is no more needed
end
end

但是你也可以使用你的重试函数:

def trythreetimes
tries = 0
begin
yield
rescue Exception => e
tries += 1
puts "Error: #{e.message}"
puts "Trying again!" if tries <= 3
retry if tries <= 3
puts "No more attempt!"
end
end

def logmeout(agent)
trythreetimes do
agent.read_timeout=2 #set the agent time out
page = agent.get('http://www.example.com/logout_url.php')
agent.history.pop() #delete this request in the history
end
end

希望对您有所帮助! ;-)

关于ruby - 使用 ruby​​ mechanize 捕获超时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7425978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com