这是我正在尝试做的事情, 并且大多数时候我都成功了:基本上,我在网站上登录,然后等待一个类出现在源代码中,然后处理源代码。
我得到的例外:
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干净的解决方案。
另一个可能也有帮助的信息:登录过程有时会很长,但是即使等待几分钟,它也会引发异常。
这是我与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)
这工作得很好!