Python Selenium 超时异常捕获
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36026676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Selenium Timeout Exception Catch
提问by PoweredByCoffee
In my threads I use a simple variable either set to '1' or '0' to indicate if it is ready to go again. Trying to debug an issue where sometimes this isn't being reset and I think I might have it.
在我的线程中,我使用一个设置为“1”或“0”的简单变量来指示它是否准备好再次运行。尝试调试有时未重置的问题,我想我可能会遇到它。
I didn't want connections timing out into some infinite load time (I believe the default for Selenium is not to have a timeout) so I used:
我不希望连接超时到一些无限加载时间(我相信 Selenium 的默认设置是没有超时)所以我使用了:
Driver.set_page_load_timeout(30)
And later on in that thread I would check
后来在那个线程中我会检查
If condition:
isrunning = 0
I had originally thought that the set_page_load_timeout would just stop it loading after 30 seconds but if I'm understanding this correctly it would actually throw an exception so I'd need to do something like:
我最初认为 set_page_load_timeout 会在 30 秒后停止加载,但如果我正确理解这一点,它实际上会抛出异常,因此我需要执行以下操作:
try:
Driver.set_page_load_timeout(30)
except:
isrunning = 0
Driver.Close()
-Do whatever else in function -
If condition:
isrunning = 0
Driver.Close()
So if it ran over 30 seconds it would close and set to 0 otherwise it would run on and get checked and set to 0 later.
因此,如果它运行超过 30 秒,它将关闭并设置为 0,否则它将继续运行并被检查并稍后设置为 0。
I appreciate this is a tiny snippet of code but the full thing is pretty long winded and I think that's the important part.
我很欣赏这是一小段代码,但完整的东西很长,我认为这是重要的部分。
I'd appreciate it if someone could confirm I have the right idea here. I'm all up for doing the testing but it's a problem which occurs once every 8 hours or so making it hard to pick apart but I think this potentially fits.
如果有人能确认我在这里有正确的想法,我将不胜感激。我完全准备好进行测试,但这是一个每 8 小时左右发生一次的问题,很难分开,但我认为这可能适合。
回答by Buaban
Almost of your code is working fine except the Driver.Close()
. It should be Driver.close()
. The TimeoutException
will be thrown when the page is not loaded within specific time. See my code below:
除了Driver.Close()
. 应该是Driver.close()
。该TimeoutException
网页时不特定的时间内装载将被抛出。请参阅下面的代码:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
Driver = webdriver.Firefox()
try:
Driver.set_page_load_timeout(1)
Driver.get("http://www.engadget.com")
except TimeoutException as ex:
isrunning = 0
print("Exception has been thrown. " + str(ex))
Driver.close()