没有任何消息的Selenium随机超时异常

时间:2013-07-02 17:50:37

标签: python selenium timeout

以下是我正在尝试做的事情,大​​部分时间我都成功了: 基本上我是在网站上登录,然后等待一个类进入源代码,然后处理源代码。

我得到的例外:

Traceback (most recent call last):
File "foo.py", line 495, in <module>
report(login, password)
File "foo.py", line 430, in report
data = bar(login, password)
File "foo.py", line 113, in 
ui.WebDriverWait(browser, 10).until(lambda browser: browser.find_elements_by_class_name("the-class-i-want"))
File "/Library/Python/2.7/site-packages/selenium/webdriver/support/wait.py", line 71, in until
raise TimeoutException(message)
selenium.common.exceptions.TimeoutException: Message: '' 

以下是代码:

from selenium import webdriver
import contextlib
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
from selenium.webdriver.support.wait import WebDriverWait

with contextlib.closing(webdriver.PhantomJS('phantomjs')) as browser:
    browser.get('mywebsite')
    login_form = browser.find_element_by_id('login-form')
    email = browser.find_element_by_name('login')
    password = browser.find_element_by_name('password')
    email.send_keys(login)
    password.send_keys(password)
    password.send_keys(Keys.RETURN)
    ui.WebDriverWait(browser, 10).until(lambda browser: browser.find_elements_by_class_name("the-class-i-want"))

我也试过了:

wait_count = 0
    while wait_count < 6:
        print wait_count
        ui.WebDriverWait(browser, 10).until(lambda browser: browser.find_elements_by_class_name("the-class-i-want"))
        if browser.find_elements_by_class_name("the-class-i-want"):
            break
        wait_count += 1

我得到同样的例外。

我目前正在尝试这个:

wait_count = 0
while wait_count < 6:
    try:
        ui.WebDriverWait(browser, 10).until(lambda browser: browser.find_elements_by_class_name("the-class-i-want"))
        if browser.find_elements_by_class_name("the-class-i-want"):
            break
    except:
        wait_count += 1
        continue

我还没有达到失败的程度,我还在测试它。

对不起,这很长。但是我想找到一个对那些随机超时的pythonic和干净的解决方案。

另一个可能有帮助的信息:签名过程有时很长,但即使等待几分钟,也会引发异常。

1 个答案:

答案 0 :(得分:5)

以下是我与Adam Goucher联系后得到的答案:

from selenium import webdriver
import contextlib
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
from selenium.webdriver.support.wait import WebDriverWait


def waiter(browser):
    elements = browser.find_elements_by_class_name('the-class-i-want')
    if len(elements) != 0:
        return elements
    return False

with contextlib.closing(webdriver.PhantomJS('phantomjs')) as browser:
    browser.get('mywebsite')
    login_form = browser.find_element_by_id('login-form')
    email = browser.find_element_by_name('login')
    password = browser.find_element_by_name('password')
    email.send_keys(login)
    password.send_keys(password)
    password.send_keys(Keys.RETURN)
    ui.WebDriverWait(browser, 10).until(waiter)

这很好用!