Last active
September 17, 2015 10:06
-
-
Save yashaka/e54c2c582cc8fb202547 to your computer and use it in GitHub Desktop.
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 ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
@contextlib.contextmanager | |
def suppress(*exceptions): | |
try: | |
yield | |
except exceptions: | |
pass | |
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): | |
time.sleep(0.1) | |
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) | |
browser.get("http://google.com/ncr") | |
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) | |
browser.get("http://google.com/ncr") | |
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 | |
browser.quit() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment