Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Notes from demo "Selenide in 15 minutes (in Python)" - version with waiting implemented from scratch and conditions as lambdas [ demoed in Minsk on 01.08.2015 ]
import contextlib
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import stopit
import time
browser = webdriver.Firefox()
def suppress(*exceptions):
except exceptions:
def wait_for(finder, condition):
result = None
with suppress(NoSuchElementException):
result = finder()
with stopit.ThreadingTimeout(4) as ctx_mgr:
while not (result and condition(result)):
with suppress(NoSuchElementException):
result = finder()
if not ctx_mgr:
raise stopit.TimeoutException("failed while waiting")
return result
class WaitingElement(object):
def __init__(self, css_selector):
self._locator = css_selector
def _finder(self):
return browser.find_element_by_css_selector(self._locator)
def __getattr__(self, item):
self.asssure(lambda element: element.is_displayed())
return getattr(self._finder(), item)
def assure(self, condition):
wait_for(self._finder, condition)
return self
def s(css_selector):
return WaitingElement(css_selector)
s("[name='q']").send_keys("selenium", Keys.ENTER)
s(".srg .g:nth-child(1)").assure(lambda element: "Selenium automates browsers" in element.text) # explicitly waiting of Selenide style (via assure instead of shouldBe)
s("[name='q']").send_keys("selenium", Keys.ENTER)
s(".srg .g:nth-child(1)").find_element_by_css_selector(".r a").click() # implicitly waiting for visibility of element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment