【问题标题】:Preventing hang with a timeout?防止超时挂起?
【发布时间】:2015-01-02 15:22:05
【问题描述】:

我制作了一个使用 Selenium Webdriver 模块导航网站的机器人。不幸的是,我注意到脚本在尝试单击按钮时有时会停止。代码很简单。我试着点击按钮,如果我不能等一下再试一次。它可以工作,但在看似随机的时间(有时在 10 分钟后,有时在几个小时后)它只是在单击按钮后停止。

while 1:
    try:
        #Try to click the button
        confirmButton = driver.find_element_by_name("confirm")
        confirmButton.click()
    #If we can't, wait a second and try again
    except:
        time.sleep(1)

我一直在考虑创建某种方法来检测这一点,从而能够使当前的点击尝试超时,但我似乎无法弄清楚如何。单线程脚本,我不能使用简单的日期时间技术,因为它永远不会运行该检查,因为它仍在等待按钮完成被点击。

编辑:有人问我怎么知道它挂了,而不是无限期地重试。我做了一个测试,我为每一行打印了一个数字,当我发生挂起时,它不会执行confirmButton.click()下面的任何行。我认为这证明它正在挂起而不是无限期地重试。或者不是?

【问题讨论】:

  • 您没有显示与您对脚本功能的描述相对应的整个代码。您显示的代码中没有再次尝试。请编辑代码,使其与您描述的内容相对应。另外,请说明您如何知道它挂起,而不仅仅是无限期重试
  • 好的,我编辑了帖子。

标签: python selenium python-3.x timeout


【解决方案1】:

您的问题可以通过超时解决:在单独的线程中启动一个函数,如果该函数未完成,则在一定时间限制后停止。

这是一个例子

from threading import Thread
from time import sleep

def threaded_function():
    confirmButton = driver.find_element_by_name("confirm")
    confirmButton.click()


if __name__ == "__main__":
    thread = Thread(target = threaded_function)
    thread.start()
    thread.join(1)# this means the thread stops after 1 second, even if it is not finished yet
    print ("thread finished...exiting")

希望对你有帮助,如果不能解决问题,请告诉我。

【讨论】:

  • 我听说过信号在 Windows 上不起作用,当我测试它时,我得到了这个错误:AttributeError: 'module' object has no attribute 'SIGALRM'。您知道在 Windows 上执行此操作的方法吗?
  • 修复了它并简化了代码,以便现在易于理解
猜你喜欢
  • 1970-01-01
  • 2010-09-17
  • 2014-12-01
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 2012-05-25
  • 2011-11-28
  • 1970-01-01
相关资源
最近更新 更多