Skip to content

Instantly share code, notes, and snippets.

@tangorboyz
Last active October 28, 2017 10:00
Show Gist options
  • Save tangorboyz/9f457854f5e1d9ca8c6bf24b45c14e15 to your computer and use it in GitHub Desktop.
Save tangorboyz/9f457854f5e1d9ca8c6bf24b45c14e15 to your computer and use it in GitHub Desktop.
Implement generic wait for element when testing with selenium instead of implicit wait
import time
import unittest
from hamcrest import assert_that, contains_string
from selenium.common.exceptions import WebDriverException
from selenium.webdriver import Chrome
def wait_for_element(browser, method_name, selector, max_wait=10):
start_time = time.time()
while True:
try:
elm = getattr(browser, method_name)(selector)
return elm
except WebDriverException as err:
if time.time() - start_time > max_wait:
raise err
time.sleep(0.5)
# Example Usage
class ExampleTesCase(unittest.TestCase):
def setUp(self):
self.browser = Chrome()
def tearDown(self):
self.browser.quit()
def test_hello_message(self):
self.browser.get('http://localhost:8000')
by_tag = self.browser.find_element_by_tag_name.__name__
h1 = wait_for_element(self.browser, by_tag, 'h1')
assert_that(h1.text, contains_string('Hello World')
@tangorboyz
Copy link
Author

Inspired by testing goat. I use this frequently when testing using behave

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment