コード例 #1
0
    def test_demo(self):

        pjsdriver = webdriver.PhantomJS("phantomjs")
        d = EventFiringWebDriver(pjsdriver, ScreenshotListener())

        d.get("http://www.google.com")
        d.find_element_by_css_selector("div.that-does-not-exist")
コード例 #2
0
class TestTacoTodos(object):

    def setup_method(self, method):
        self.driver = EventFiringWebDriver(remote_webdriver, MaListener())
        self.current_method_name = method.__name__

    def teardown_method(self, method):
        self.driver.close()
        self.driver.quit()

    def test_todo_counts(self):
        tacotodos = TacoTodoPage(self.driver).open()
        tacotodos.new_todo = 'Bean and egg taco \n'
        tacotodos.new_todo = 'Potato, egg & cheese \n'
        tacotodos.new_todo = 'Nopales y huevos\n'
        tacotodos.new_todo = 'Crispy taco\n'
        tacotodos.new_todo = 'Cruspy taco\n'
        tacotodos.new_todo = 'Crepes\n'
        assert 6 == tacotodos.todos_remaining
        tacotodos.complete_all_todos()
        assert 6 == tacotodos.todos_completed
        assert 6 == tacotodos.todos_listed
        assert 0 == tacotodos.todos_remaining
        tacotodos.clear_completed_todos()
        assert 0 == tacotodos.todos_listed
        assert 0 == tacotodos.todos_completed
コード例 #3
0
 def test_should_unwrap_element_args_when_calling_scripts(self):
     ef_driver = EventFiringWebDriver(self.driver, AbstractEventListener())
     ef_driver.get(self._pageURL("javascriptPage"))
     button = ef_driver.find_element_by_id("plainButton")
     value = ef_driver.execute_script(
         "arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble']",
         button)
     self.assertEqual("plainButton", value)
コード例 #4
0
 def test_should_unwrap_element_args_when_calling_scripts(self, driver, log, pages):
     ef_driver = EventFiringWebDriver(driver, AbstractEventListener())
     ef_driver.get(pages.url("javascriptPage.html"))
     button = ef_driver.find_element_by_id("plainButton")
     value = ef_driver.execute_script(
         "arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble']",
         button)
     assert "plainButton" == value
コード例 #5
0
    def test_should_fire_navigation_events(self):
        log = self.log 
                
        class TestListener(AbstractEventListener):
            def before_navigate_to(self, url, driver):
                log.write(("before_navigate_to %s" % url.split("/")[-1]).encode())
            def after_navigate_to(self, url, driver):
                log.write(("after_navigate_to %s" % url.split("/")[-1]).encode())
            def before_navigate_back(self, driver):
                log.write(b"before_navigate_back")
            def after_navigate_back(self, driver):
                log.write(b"after_navigate_back")
            def before_navigate_forward(self, driver):
                log.write(b"before_navigate_forward")
            def after_navigate_forward(self, driver):
                log.write(b"after_navigate_forward")
            
        ef_driver = EventFiringWebDriver(self.driver, TestListener())            
        ef_driver.get(self._pageURL("formPage"))
        ef_driver.find_element(by=By.ID, value="imageButton").submit()
        self.assertEqual(ef_driver.title, "We Arrive Here")

        ef_driver.back()
        self.assertEqual(ef_driver.title, "We Leave From Here")

        ef_driver.forward()
        self.assertEqual(ef_driver.title, "We Arrive Here")        
       
        self.assertEqual(b"before_navigate_to formPage.html" \
                + b"after_navigate_to formPage.html" \
                + b"before_navigate_back" \
                + b"after_navigate_back" \
                + b"before_navigate_forward" \
                + b"after_navigate_forward", log.getvalue())
コード例 #6
0
def test_missing_attributes_raise_error(driver, pages):
    ef_driver = EventFiringWebDriver(driver, AbstractEventListener())

    with pytest.raises(AttributeError):
        ef_driver.attribute_should_not_exist

    ef_driver.get(pages.url("readOnlyPage.html"))
    element = ef_driver.find_element_by_id("writableTextInput")

    with pytest.raises(AttributeError):
        element.attribute_should_not_exist
コード例 #7
0
    def test_should_call_listener_when_an_exception_is_thrown(self, driver, log, pages):
        class TestListener(AbstractEventListener):
            def on_exception(self, exception, driver):
                if isinstance(exception, NoSuchElementException):
                    log.write(b"NoSuchElementException is thrown")

        ef_driver = EventFiringWebDriver(driver, TestListener())
        ef_driver.get(pages.url("simpleTest.html"))
        with pytest.raises(NoSuchElementException):
            ef_driver.find_element(By.ID, "foo")
        assert b"NoSuchElementException is thrown" == log.getvalue()
コード例 #8
0
    def test_should_be_able_to_access_wrapped_instance_from_event_calls(self):
        driver = self.driver

        class TestListener(AbstractEventListener):
            def before_navigate_to(self, url, d):
                assert driver is d

        ef_driver = EventFiringWebDriver(driver, TestListener())
        wrapped_driver = ef_driver.wrapped_driver
        assert driver is wrapped_driver

        ef_driver.get(self._pageURL("simpleTest"))
コード例 #9
0
    def test_should_fire_click_event(self, driver, log, pages):
        class TestListener(AbstractEventListener):
            def before_click(self, element, driver):
                log.write(b"before_click")

            def after_click(self, element, driver):
                log.write(b"after_click")

        ef_driver = EventFiringWebDriver(driver, TestListener())
        ef_driver.get(pages.url("clicks.html"))
        ef_driver.find_element(By.ID, "overflowLink").click()
        assert ef_driver.title == "XHTML Test Page"

        assert b"before_click" + b"after_click" == log.getvalue()
コード例 #10
0
    def test_should_fire_find_event(self):
        log = self.log

        class TestListener(AbstractEventListener):

            def before_find(self, by, value, driver):
                log.write(("before_find by %s %s" % (by, value)).encode())

            def after_find(self, by, value, driver):
                log.write(("after_find by %s %s" % (by, value)).encode())

        ef_driver = EventFiringWebDriver(self.driver, TestListener())
        ef_driver.get(self._pageURL("simpleTest"))
        e = ef_driver.find_element_by_id("oneline")
        self.assertEqual("A single line of text", e.text)

        e = ef_driver.find_element_by_xpath("/html/body/p[1]")
        self.assertEqual("A single line of text", e.text)

        ef_driver.get(self._pageURL("frameset"))
        elements = ef_driver.find_elements_by_css_selector("frame#sixth")
        self.assertEqual(1, len(elements))
        self.assertEqual("frame", elements[0].tag_name.lower())
        self.assertEqual("sixth", elements[0].get_attribute("id"))

        self.assertEqual(
            b"before_find by id oneline"
            b"after_find by id oneline"
            b"before_find by xpath /html/body/p[1]"
            b"after_find by xpath /html/body/p[1]"
            b"before_find by css selector frame#sixth"
            b"after_find by css selector frame#sixth", log.getvalue())
コード例 #11
0
    def test_should_fire_find_event(self, driver, log, pages):

        class TestListener(AbstractEventListener):

            def before_find(self, by, value, driver):
                log.write(("before_find by %s %s" % (by, value)).encode())

            def after_find(self, by, value, driver):
                log.write(("after_find by %s %s" % (by, value)).encode())

        ef_driver = EventFiringWebDriver(driver, TestListener())
        ef_driver.get(pages.url("simpleTest.html"))
        e = ef_driver.find_element_by_id("oneline")
        assert "A single line of text" == e.text

        e = ef_driver.find_element_by_xpath("/html/body/p[1]")
        assert "A single line of text" == e.text

        ef_driver.get(pages.url("frameset.html"))
        elements = ef_driver.find_elements_by_css_selector("frame#sixth")
        assert 1 == len(elements)
        assert "frame" == elements[0].tag_name.lower()
        assert "sixth" == elements[0].get_attribute("id")

        assert (b"before_find by id oneline"
                b"after_find by id oneline"
                b"before_find by xpath /html/body/p[1]"
                b"after_find by xpath /html/body/p[1]"
                b"before_find by css selector frame#sixth"
                b"after_find by css selector frame#sixth") == log.getvalue()
コード例 #12
0
 def test_should_fire_click_event(self):
     log = self.log
     
     class TestListener(AbstractEventListener):            
         def before_click(self, element, driver):
             log.write(b"before_click")
         def after_click(self, element, driver):
             log.write(b"after_click")
         
     ef_driver = EventFiringWebDriver(self.driver, TestListener())            
     ef_driver.get(self._pageURL("clicks"))        
     ef_driver.find_element(By.ID, "overflowLink").click() 
     self.assertEqual(ef_driver.title, "XHTML Test Page")
     
     self.assertEqual(b"before_click" + b"after_click", log.getvalue())
コード例 #13
0
    def test_should_call_listener_when_an_exception_is_thrown(self):
        log = self.log

        class TestListener(AbstractEventListener):
            def on_exception(self, exception, driver):
                if isinstance(exception, NoSuchElementException):
                    log.write(b"NoSuchElementException is thrown")

        ef_driver = EventFiringWebDriver(self.driver, TestListener())
        ef_driver.get(self._pageURL("simpleTest"))
        try:
            ef_driver.find_element(By.ID, "foo")
            self.fail("Expected exception to be propagated")
        except NoSuchElementException:
            pass
        self.assertEqual(b"NoSuchElementException is thrown", log.getvalue())
コード例 #14
0
    def test_should_fire_change_value_event(self, driver, log, pages):

        class TestListener(AbstractEventListener):

            def before_change_value_of(self, element, driver):
                log.write(b"before_change_value_of")

            def after_change_value_of(self, element, driver):
                log.write(b"after_change_value_of")

        ef_driver = EventFiringWebDriver(driver, TestListener())
        ef_driver.get(pages.url("readOnlyPage.html"))
        element = ef_driver.find_element_by_id("writableTextInput")
        element.clear()
        assert "" == element.get_attribute("value")

        ef_driver.get(pages.url("javascriptPage.html"))
        keyReporter = ef_driver.find_element(by=By.ID, value="keyReporter")
        keyReporter.send_keys("abc def")
        assert keyReporter.get_attribute("value") == "abc def"

        assert (b"before_change_value_of"
                b"after_change_value_of"
                b"before_change_value_of"
                b"after_change_value_of") == log.getvalue()
コード例 #15
0
    def test_should_fire_change_value_event(self):
        log = self.log

        class TestListener(AbstractEventListener):

            def before_change_value_of(self, element, driver):
                log.write(b"before_change_value_of")

            def after_change_value_of(self, element, driver):
                log.write(b"after_change_value_of")

        ef_driver = EventFiringWebDriver(self.driver, TestListener())
        ef_driver.get(self._pageURL("readOnlyPage"))
        element = ef_driver.find_element_by_id("writableTextInput")
        element.clear()
        self.assertEqual("", element.get_attribute("value"))

        ef_driver.get(self._pageURL("javascriptPage"))
        keyReporter = ef_driver.find_element(by=By.ID, value="keyReporter")
        keyReporter.send_keys("abc def")
        self.assertEqual(keyReporter.get_attribute("value"), "abc def")

        self.assertEqual(
            b"before_change_value_of"
            b"after_change_value_of"
            b"before_change_value_of"
            b"after_change_value_of", log.getvalue())
コード例 #16
0
ファイル: surfer.py プロジェクト: rotsee/SDRSkrejper
    def __init__(self, delay=1, browser="firefox"):
        """delay: Number of extra seconds to wait when a page is
           supposedly loaded. Try raising this in case of weird errors.

           browser: `firefox` or `chrome`. The ChromeDriver executable for your
           OS must be inside the bin directory for Chrome to work. Get it from:
           http://chromedriver.storage.googleapis.com/index.html
        """
        self.extra_delay = delay  # extra time to wait after each operation (s)
        self.temp_dir = mkdtemp()

        self.vdisplay = Xvfb()
        self.vdisplay.start()
        if browser == "firefox":
            profile = FirefoxProfile()
            # Open links in same window
            profile.set_preference("browser.link.open_newwindow", 1)
            # Download to temp dir, for files we can't open inline
            profile.set_preference("browser.download.dir", self.temp_dir)
            profile.set_preference("browser.download.folderList", 2)
            profile.set_preference("browser.download.manager.showWhenStarting",
                                   "False")
            profile.set_preference("browser.helperApps.neverAsk.saveToDisk",
                                   "application/msword, application/vnd.ms-word, application/rtf, application/octet-stream")

            # Add extension for overriding Content-Disposition headers, etc
            extensions_dir = os_sep.join(['bin', 'firefox-plugins-enabled'])
            for filename in listdir(extensions_dir):
                fullfilename = os_sep.join([extensions_dir, filename])
                profile.add_extension(extension=fullfilename)

            driver = Firefox(profile)
        elif browser == "chrome":
            # Add extension for overriding Content-Disposition headers
            options = ChromeOptions()
            options.add_extension('bin/undisposition.crx')
            driver = Chrome(executable_path='bin/chromedriver',
                            chrome_options=options)
        else:
            raise Exception("Not a valid browser name")

        self.selenium_driver = EventFiringWebDriver(driver, CustomListener())
        """selenium_driver is a EventFiringWebDriver, so that it can
           trigger javascript event
        """
        self.browser_version = " ".join([
            self.selenium_driver.capabilities['browserName'],
            self.selenium_driver.capabilities['version']])  # 'Firefox 33.0'
コード例 #17
0
def test_should_fire_navigation_events(driver, log, pages):

    class EventListener(AbstractEventListener):

        def before_navigate_to(self, url, driver):
            log.write(("before_navigate_to %s" % url.split("/")[-1]).encode())

        def after_navigate_to(self, url, driver):
            log.write(("after_navigate_to %s" % url.split("/")[-1]).encode())

        def before_navigate_back(self, driver):
            log.write(b"before_navigate_back")

        def after_navigate_back(self, driver):
            log.write(b"after_navigate_back")

        def before_navigate_forward(self, driver):
            log.write(b"before_navigate_forward")

        def after_navigate_forward(self, driver):
            log.write(b"after_navigate_forward")

    ef_driver = EventFiringWebDriver(driver, EventListener())
    ef_driver.get(pages.url("formPage.html"))
    ef_driver.find_element(by=By.ID, value="imageButton").submit()
    WebDriverWait(ef_driver, 5).until(lambda d: d.title == "We Arrive Here")
    assert ef_driver.title == "We Arrive Here"

    ef_driver.back()
    assert ef_driver.title == "We Leave From Here"

    ef_driver.forward()
    assert ef_driver.title == "We Arrive Here"

    assert (b"before_navigate_to formPage.html"
            b"after_navigate_to formPage.html"
            b"before_navigate_back"
            b"after_navigate_back"
            b"before_navigate_forward"
            b"after_navigate_forward") == log.getvalue()
コード例 #18
0
from page.google.news import NewsGooglePage
from selenium.webdriver.support.events import EventFiringWebDriver
from webdriverwrapper.driver import WebDriver

from _corpus.retrieval.webdriverwrapper.listener import WebDriverEventListener

sys.path.append('.')

desired_capabilities = {'browserName': 'chrome'}
command_executor = "http://127.0.0.1:4444/wd/hub"
news_us = "https://news.google.com/?ned=us"  # ned=us for us edition
news_pe = "https://news.google.com/?ned=es_pe"

remote_webdriver = WebDriver(desired_capabilities=desired_capabilities,
                             command_executor=command_executor)
driver = EventFiringWebDriver(remote_webdriver, WebDriverEventListener())
google = NewsGooglePage(driver)

update = False
words = [
    "chambear", "bamba", "jama", "chancar", "chela", "papayita", "jatear",
    "jato", "tombo", "tranca", "huasca", "choborra", "cacharro", "chongo",
    "chupodromo", "fercho", "huachimán", "latear", "lompa", "mitra", "jeta",
    "moquear", "ni michi", "ñanga", "ñoba", "telo", "panudo"
]
for word in words:
    file = "pkz/" + word + ".pkz"
    if not os.path.exists(file) or update:
        google.open(news_pe)
        links = google.get_results_links(word, 1, 2, True)
        print("links:", len(links), "word:", "'" + word + "'")
コード例 #19
0
ファイル: test_day_10_1.py プロジェクト: dmchu/Ellie
 def setUp(self):
     # self.driver = webdriver.Chrome()
     self.driver = EventFiringWebDriver(webdriver.Chrome(desired_capabilities={"chromeOptions": {"args": ['--start-fullscreen']}}),MyListener())
     self.driver.get("http://localhost/litecart/admin")
     self.wait = WebDriverWait(self.driver,10)
コード例 #20
0
ファイル: test_9.py プロジェクト: roman-kachur/selenium_2019
def driver(request):
    wd = EventFiringWebDriver(webdriver.Chrome(), MyListener())
    wd.implicitly_wait(DEFAULT_TIMEOUT)
    request.addfinalizer(wd.quit)
    return wd
コード例 #21
0
ファイル: uitests.py プロジェクト: rkochath/rk-microblog
class GoogleTestCase(unittest.TestCase):

    def setUp(self):

        self.driver = Firefox()
        self.browser = EventFiringWebDriver(self.driver, MyListener())
        self.addCleanup(self.browser.quit)

    def testContractslist(self):
        self.browser.get("http://localhost/contracts_list")

        inputElement = self.browser.find_element_by_name("openid")
        inputElement.send_keys("https://me.yahoo.com")
        loginElement = self.browser.find_element_by_name("sign_in")
        loginElement.click()
 
        loginBox = self.browser.find_element_by_id("username");
        loginBox.send_keys("techkoch")
        pwBox = self.browser.find_element_by_id("passwd");
        pwBox.send_keys("Holtsville137")
	 
        signinBtn = self.browser.find_element_by_id(".save");
        signinBtn.click()
 
	wait = WebDriverWait(self.browser, 100)
	wait.until(EC.title_contains('Contracts'))
	newbtn = WebDriverWait(self.browser, 100).until(lambda x: x.find_element_by_name("new_btn"))	
	newbtn.click()

    def testPost(self):
        self.browser.get("http://localhost")
        inputElement = self.browser.find_element_by_name("openid")
        inputElement.send_keys("https://me.yahoo.com")
        loginElement = self.browser.find_element_by_name("sign_in")
        loginElement.click()
 
        loginBox = self.browser.find_element_by_id("username");
        loginBox.send_keys("techkoch")
        pwBox = self.browser.find_element_by_id("passwd");
        pwBox.send_keys("Holtsville137")
	 
        signinBtn = self.browser.find_element_by_id(".save");
        signinBtn.click()
	wait = WebDriverWait(self.browser, 100)
	wait.until(EC.title_contains('microblog'))

	#wait = WebDriverWait(self.browser, 100)
        #self.assertIn('microblog', self.browser.title)
	#post = wait.until(EC.presence_of_element_located(By.ID,'post'))
	post = WebDriverWait(self.browser, 100).until(lambda x: x.find_element_by_id("post"))	

	#post = self.browser.find_element_by_name("post")
	post.send_keys("Automated post...")
	savepost = self.browser.find_element_by_name("savepost")
	savepost.click()
コード例 #22
0
def driver(request):
    driver = EventFiringWebDriver(webdriver.Chrome(), MyListener())
    yield driver
    request.addfinalizer(driver.quit)
コード例 #23
0
from selenium.webdriver import Firefox
from selenium.webdriver.support.events import(
    AbstractEventListener,
    EventFiringWebDriver,
)

class Escuta(AbstractEventListener):
    def before_click(self,elemento,webdriver):
        if elemento.tag_name =='input'
            print(webdriver.find_element_by_tag_name('p').text)
        print(f'antes do click no {elemento.tag_name}')

    def after_click(self,elemento,webdriver):
        if elemento.tag_name =='input'
            print(webdriver.find_element_by_tag_name('p').text)
        print(f'depois do click no {elemento.tag_name}')

browser = Firefox()

rapi_browser = EventFiringWebDriver(browser,Escuta())

browser.get('https://selenium.dunossauro.live/aula_07_d')

input_de_texto = rapi_browser.find_element_by_tag_name('input')
span=rapi_browser.find_element_by_tag_name('span')
p=rapi_browser.find_element_by_tag_name('p')


input_de_texto.click()
print('Tó clicando')
コード例 #24
0
        print("after_navigate_forward")

    def before_navigate_forward(self, driver):
        print("before_navigate_forward")

    def after_navigate_back(self, driver):
        print("after_navigate_back")

    def before_navigate_back(self, driver):
        print("before_navigate_back")

    def before_change_value_of(self, element, driver):
        print("before_change_value_of")


d = EventFiringWebDriver(b, EventListeners())

d.get('https://www.cnn.com')
d.implicitly_wait(20)
d.get('https://www.google.de')
d.implicitly_wait(20)
d.back()


def on_click(x, y, button, pressed):
    if pressed:
        print('Mouse clicked')
        time.sleep(2)
        print("Navigation to: %s " % b.current_url)

コード例 #25
0
def driver(request):
    wd = EventFiringWebDriver(webdriver.Chrome(), MyListener())
    request.addfinalizer(wd.quit)
    return wd
コード例 #26
0
ファイル: eventdriver.py プロジェクト: jinmoo21/PWDriver
class EventDriverTest(unittest.TestCase):
    def setUp(self):
        core1 = WebDriverFactory().launch()
        core2 = WebDriverFactory().launch()
        self.driver1 = EventFiringWebDriver(core1, EventListener())
        self.driver2 = EventFiringWebDriver(core2, EventListener())
        self.driver1.maximize_window()
        self.wait1 = WebDriverWait(self.driver1, 5)
        self.wait2 = WebDriverWait(self.driver2, 5)

    def tearDown(self):
        self.driver2.quit()
        self.driver1.quit()

    def test_something(self):
        self.driver1.get('https://www.google.com')
        logger.info(self.driver1.title)
        self.assertIn(self.driver1.title, 'Google')
        self.driver1.get('https://www.naver.com')
        news_btn1 = self.driver1.find_element(By.CSS_SELECTOR, '.link_news')
        news_btn1.click()
        logger.info(self.driver1.current_url)
        self.assertTrue(self.wait1.until(expected_conditions.url_contains('https://news.naver.com')))

        self.driver2.get('https://www.google.com')
        logger.info(self.driver2.title)
        self.assertIn(self.driver2.title, 'Google')
        self.driver2.get('https://www.naver.com')
        news_btn2 = self.driver2.find_element(By.CSS_SELECTOR, '.link_join')
        news_btn2.click()
        logger.info(self.driver2.current_url)
        self.assertTrue(self.wait2.until(expected_conditions.url_contains('https://nid.naver.com')))
コード例 #27
0
sleep(4)

class Escuta(AbstractEventListener):
    def before_navigate_to(self, url, webdriver):
        print(f"O Link: {url}")
    
    def before_click(self, element, webdriver):
        span = webdriver.find_element_by_tag_name("span")
        print(span.text)
        # print("Antes do Click")
        
    def after_click(self, element, webdriver):
        span = webdriver.find_element_by_tag_name("span")
        print(span.text)
        # print("Depois do click")
        
wraperBroswer = EventFiringWebDriver(driver, Escuta())     
        
wraperBroswer.get(url)      
        

        
input_ = wraperBroswer.find_element_by_tag_name("input")
span = wraperBroswer.find_element_by_tag_name("span")
p = wraperBroswer.find_element_by_tag_name("p")


input_.click()

wraperBroswer.get(url2) 
コード例 #28
0
def test_using_kwargs(driver, pages):
    ef_driver = EventFiringWebDriver(driver, AbstractEventListener())
    ef_driver.get(pages.url("javascriptPage.html"))
    ef_driver.get_cookie(name="cookie_name")
    element = ef_driver.find_element_by_id("plainButton")
    element.get_attribute(name="id")
コード例 #29
0
from selenium import webdriver
from selenium.webdriver.support.events import AbstractEventListener, EventFiringWebDriver


class MyListener(AbstractEventListener):
    def before_navigate_to(self, url, driver):
        print("Before navigate to: {}".format(url))

    def after_navigate_to(self, url, driver):
        print("After navigate to: {}".format(url))


driver = webdriver.Chrome('./chromedriver')
ef = EventFiringWebDriver(driver, MyListener())
ef.get('http://python.org')
driver.close()
コード例 #30
0
    'password': '******'
}

nav = Firefox()

nav.get('https://selenium.dunossauro.live/exercicio_07')


class Escuta(AbstractEventListener):
    def before_click(self, elem, browser):
        print(elem.find_element_by_tag_name('label').text)

    def after_click(self, elem, browser):
        print(elem.find_element_by_tag_name('label').text)


listen_nav = EventFiringWebDriver(nav, Escuta())

time.sleep(3)

fields = listen_nav.find_elements_by_css_selector('.form-group')

for ele in fields:
    field = ele.find_element_by_tag_name('input').wrapped_element
    intype = field.get_attribute('type')
    if intype == 'submit':
        field.click()
    else:
        ele.click()
        field.send_keys(dict_types[intype])
コード例 #31
0
from selenium import webdriver
from selenium.webdriver.support.events import EventFiringWebDriver
from mylistener import MyListener

chrome = webdriver.Chrome()
listener = MyListener()

ef_chrome = EventFiringWebDriver(chrome, listener)

ef_chrome.get('http://pythonclub.com.br')

try:
    """
        Propositalmente ira gerar uma exception pois a classe nao existe.
        O evento "on_exception" deve ser chamado
    """
    post = ef_chrome.find_element_by_class_name('post-title')
except:
    pass

post = ef_chrome.find_element_by_class_name('post-tile')
post.click()

ef_chrome.close()
コード例 #32
0
    def after_close(self, driver):
        print "Depois de fechar a pagina"

    def on_exception(self, exeception, driver):
        print "Ocorreu um erro"


if __name__ == '__main__':
    # instancia do navegador
    firefox = webdriver.Firefox()

    # instancia do listener
    listener = MyListener()

    # instancia do navegador com os eventos monitorados
    ef_firefox = EventFiringWebDriver(firefox, listener)

    # abrir página da python club
    ef_firefox.get('http://pythonclub.com.br/')

    try:
        """
            Propositalmente irá gerar uma exception pois a classe não existe.
            O evento "on_exception" deve ser chamado
        """
        post = ef_firefox.find_element_by_class_name('post-tile')
    except:
        pass

    # localizamos o primeiro post
    post = ef_firefox.find_element_by_class_name('post-title')
コード例 #33
0
class LostHatSmokeTests(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.base_url = 'https://autodemo.testoneo.com/en/'
        self.login_url = self.base_url + 'login'
        self.clothes_product_url = self.base_url + '3-clothes'
        self.accessories_product_url = self.base_url + '6-accessories'
        self.art_product_url = self.base_url + '9-art'
        driver = webdriver.Chrome(
            executable_path=r"C:\Users\andrejew\PycharmProjects\chromedriver")
        self.ef_driver = EventFiringWebDriver(driver, ScreenshotListener())

    @classmethod
    def tearDownClass(self):
        self.ef_driver.quit()

    @screenshot_decorator
    def test_base_page_title(self):
        expected_title = "Lost Hat"
        self.assert_title(self.base_url, expected_title)

    @screenshot_decorator
    def test_product_clothes_page_title(self):
        url = "https://autodemo.testoneo.com/en/3-clothes"
        expected_title = "Clothes"
        self.assert_title(url, expected_title)

    @screenshot_decorator
    def test_accessories_product(self):
        url = "https://autodemo.testoneo.com/en/6-accessories"
        expected_title = "Accessories"
        self.assert_title(url, expected_title)

    @screenshot_decorator
    def test_art_product(self):
        url = 'https://autodemo.testoneo.com/en/9-art'
        expected_title = "Art"
        self.assert_title(url, expected_title)

    def get_page_title(self, url):
        self.ef_driver.get(url)
        return self.ef_driver.title

    @screenshot_decorator
    def test_smoke_search_on_main_page(self):
        search_phase = 'mug'
        search_input_xpath = '//*[@name="s"]'
        result_element_xpath = '//*[@class="product-miniature js-product-miniature"]'
        minimum_expected_elements = 5
        self.ef_driver.get(self.base_url)
        search_input_element = self.ef_driver.find_element_by_xpath(
            search_input_xpath)
        search_input_element.send_keys(search_phase)
        search_input_element.send_keys(Keys.ENTER)
        result_elements = self.ef_driver.find_elements_by_xpath(
            result_element_xpath)
        self.assertGreaterEqual(
            len(result_elements), minimum_expected_elements,
            f'Actual number of elements found: {len(result_elements)}; \ '
            f'expected was {minimum_expected_elements} or more')

    def assert_title(self, url, expected_title):
        actual_title = self.get_page_title(url)
        self.assertEqual(expected_title, actual_title,
                         f'Result differ than expected for page {url}')
コード例 #34
0
def test_using_kwargs(driver, pages):
    ef_driver = EventFiringWebDriver(driver, AbstractEventListener())
    ef_driver.get(pages.url("javascriptPage.html"))
    ef_driver.get_cookie(name="cookie_name")
    element = ef_driver.find_element_by_id("plainButton")
    element.get_attribute(name="id")
コード例 #35
0
from walmart_bot import WalmartBot
# chromedriver that avoids triggering bot detection:
import undetected_chromedriver as uc
# Since undetected_chromedriver requires Chromium 87:
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.events import EventFiringWebDriver
# Contains login credentials, credit card info, and such:
import personal_info
# Listener class
from event_listeners import BotListener

options = Options()
# I have the latest build of Chromium in my selenium bot's directory:
options.binary_location = "./chrome-linux/chrome"

# Get the latest chromium build for Linux here:
# https://chromium.woolyss.com/#linux

if __name__ == "__main__":
    # Create instance of webdriver
    bot_driver = uc.Chrome(chrome_options=options)
    bot_driver.implicitly_wait(10)
    event_driver = EventFiringWebDriver(bot_driver, BotListener())
    # Create instance of bot
    bot = WalmartBot(event_driver, personal_info.walmart_profile)
    # Run bot on product page:
    bot.run(
        "https://www.walmart.com/ip/For-Raspberry-Pi-4-B-Touch-Screen-with-Case-EEEkit-3-5-inch-Touchscreen-Support-320x480-Monitor-TFT-LCD-Game-Display-for-Raspberry-Pi-4-B/430357329"
    )
コード例 #36
0
        print(f"Voltando para página anterior")

    def before_click(self, elemento, webdriver):
        if elemento.tag_name == 'input':
            print(webdriver.find_element_by_tag_name('span').text)
        print(f'antes  do click no {elemento.tag_name}')

    def after_click(self, elemento, webdriver):
        if elemento.tag_name == 'input':
            print(webdriver.find_element_by_tag_name('span').text)
        print(f'depois do click no {elemento.tag_name}')


browser = Firefox()

rapi_browser = EventFiringWebDriver(browser, Escuta())

rapi_browser.get('https://selenium.dunossauro.live/aula_07_d')

input_de_texto = rapi_browser.find_element_by_tag_name('input')
span = rapi_browser.find_element_by_tag_name('span')
p = rapi_browser.find_element_by_tag_name('p')

input_de_texto.click()
span.click()

rapi_browser.get('https://selenium.dunossauro.live/aula_07_c')

rapi_browser.back()

browser.quit()
コード例 #37
0
 def _wrap_event_firing_webdriver(self, driver):
     if not self.ctx.event_firing_webdriver:
         return driver
     self.debug('Wrapping driver to event_firing_webdriver.')
     return EventFiringWebDriver(driver, self.ctx.event_firing_webdriver())
コード例 #38
0
 def setUpClass(cls):
     edriver = webdriver.Chrome(
         executable_path=TestData.CHROME_EXECUTABLE_PATH)
     cls.driver = EventFiringWebDriver(edriver, ScreenshotListener())
     cls.driver.maximize_window()
     cls.driver.implicitly_wait(20)
コード例 #39
0
ファイル: uitests.py プロジェクト: rkochath/rk-microblog
    def setUp(self):

        self.driver = Firefox()
        self.browser = EventFiringWebDriver(self.driver, MyListener())
        self.addCleanup(self.browser.quit)
コード例 #40
0
 def test_should_unwrap_element_args_when_switching_frames(self, driver, log, pages):
     ef_driver = EventFiringWebDriver(driver, AbstractEventListener())
     ef_driver.get(pages.url("iframes.html"))
     frame = ef_driver.find_element_by_id("iframe1")
     ef_driver.switch_to.frame(frame)
     assert "click me!" == ef_driver.find_element_by_id("imageButton").get_attribute("alt")
コード例 #41
0
ファイル: webdriver.py プロジェクト: GelLiNN/tagcompare
def __setup_phantomjs_webriver(screenshot_on_exception=False):
    driver = webdriver.PhantomJS()
    if screenshot_on_exception:
        driver = EventFiringWebDriver(driver, ScreenshotListener())
    driver.set_window_size(1920, 1080)
    return driver
コード例 #42
0
def chrome_browser(request):
    options = webdriver.ChromeOptions()
    options.add_argument("start-maximized")
    wd = EventFiringWebDriver(webdriver.Chrome(), MyListener())
    request.addfinalizer(wd.quit)
    return wd
コード例 #43
0
class Browser:

    def __init__(self):
        self.new_driver()

    _driver_instance = None
    _session_snapshots = {}

    def new_driver(self):
        command_executor = "{0}://{1}:{2}{3}".format(
            SettingsManager._config['protocol'],
            SettingsManager.get('host'),
            SettingsManager.get('port'),
            SettingsManager.get('path')
        )

        remote_driver = webdriver.Remote(
            command_executor=command_executor,
            desired_capabilities=SettingsManager.get('capabilities')
        )

        if session.use_listener:
            self._driver_instance = EventFiringWebDriver(remote_driver, ElementHighlightListener())
        else:
            self._driver_instance = remote_driver

        self._driver_instance.implicitly_wait(SettingsManager.get('implicit_timeout'))
        self._driver_instance.maximize_window()

        return self._driver_instance

    def get_driver(self):
        if not self._driver_instance:
            self.new_driver()
        return self._driver_instance

    def close_driver(self):
        if self._driver_instance:
            self._driver_instance.quit()
            self._driver_instance = None

    def attach_file(self, element, file_name):
        log_step(f"Attach file {file_name}")
        file_path = session.data_dir.joinpath(file_name)

        if not Path.exists(file_path):
            raise IOError(f"File does not exist: {file_path}")

        self.get_driver().file_detector = LocalFileDetector()
        self.fill_field(element, str(file_path))

    def open(self, path):
        """
        Переходит по относительному URL (/login, /admin/users, etc ...)

        Args:
            path (str): Путь

        Examples:
            >>> browser.open("/")
            # На главную

            >>> browser.open("/admin")
            # В админку
        """
        url = urljoin(SettingsManager.get('url'), path)
        log_step(f"Open {url}")
        self.get_driver().get(url)

    def open_url(self, url):
        """
        Переходит по абсолютному URL.

        Args:
            url (str): URL

        Examples:
            >>> browser.open_url("https://google.com")
        """
        log_step(f"Open URL {url}")
        self.get_driver().get(url)

    def refresh(self):
        """
        Обновляет страницу
        """
        log_step("Refresh page")
        self.get_driver().refresh()

    def grab_console_log(self):
        '''
        Получить лог браузерной консоли. Буффер очищается после каждого запроса.
        Требует сapability ``loggingPrefs: { browser: 'INFO' }``.

        Returns:
            list[str]: список строк
        '''
        log_step("Grab browser console log")
        return self.get_driver().get_log('browser')

    def grab_page_html(self):
        """
        Возвращает html всей страницы.

        Returns:
            str: html
        """
        log_step("Grab page html")
        return self.get_driver().page_source

    def grab_html_from(self, element):
        """
        Возвращает html элемента.

        Returns:
            str: html
        """
        log_step(f"Grab html from {element}")
        el = self._match_first_or_fail(element)
        return el.get_attribute('outerHTML')

    def clear_field(self, input_element):
        """
        Очищает поле.

        Args:
            input_element (Element): Поле ввода

        Examples:
            >>> browser.clear_field(Element("#input"))
        """
        log_step(f"Clear field {input_element}")
        el = self._match_first_or_fail(input_element)
        el.clear()

    def fill_field(self, element, text):
        """
        Заполняет текстом поле ввода

        Args:
            element (Element): Поле ввода
            text    (str):  Текст

        Examples:
            >>> browser.fill_field(Element("//input[@type='text']"), "Hello World!")
        """
        log_step(f"Fill field {element} with '{text}'")
        el = self._match_first_or_fail(element)
        el.clear()
        el.send_keys(text)

    def fill_field_with_delay(self, element, text, delay=0.1):
        """
        Заполняет текстом поле ввода делая паузу между каждым символом.

        Args:
            element (Element): Поле ввода
            text    (str):  Текст
            delay   (float, optional): Задержка (сек.), по умолчанию 0.1

        Examples:
            >>> browser.fill_field(Element("//input[@type='text']"), "Hello World!", 0.2)
        """
        log_step(f"Fill field {element} with '{text}' & delay '{delay}'")
        field = self._match_first_or_fail(element)
        for ch in text:
            field.send_keys(ch)
            self.sleep(delay)

    def press_key(self, element, *chars):
        """
        Нажимает кнопки.
        Чтобы ввести символы с модификатором (ctrl, alt, shift, meta), передай кортеж
        у которого первый элемент модификатор, а второй текст.

        Args:
            element (Element):      Элемент, куда посылать нажатия
            *chars  (str|tuple):    Что вводить. Может быть строкой или кортежем в модификатором

        Examples:
            Дано: поле, в которое введён текст ``old``:\n
            ``<input id="input" value="old" />``

            >>> from selenium.webdriver.common.keys import Keys
            >>> field = Find("#input")
            >>> browser.press_key(field, "A")
            oldA
            >>> browser.press_key(field, ("ctrl", "a"), "new")
            new
            >>> browser.press_key(field, ("shift", "333"), "2", "x")
            old###2x
            >>> browser.press_key(field, Keys.BACKSPACE)
            ol
        """
        log_step(f"Press keys {chars} on {element}")
        el = self._match_first_or_fail(element)
        for char in chars:
            el.send_keys(*self._convert_key_modifier(char))

    def append_field(self, element, text):
        """
        Присоединяет переданный текст к элементу.

        Args:
            element     (Element): элемент
            text        (str): текст

        Examples:
            >>> browser.append_field(Find('#field'), 'foo bar baz')
        """
        log_step(f"Append field {element}, '{text}'")
        field = self._match_first_or_fail(element)
        field.send_keys(text)

    def wait_for_element_visible(self, element, timeout=5, poll_frequency=0.5):
        """
        Ждёт до ``timeout`` сек. видимости элемента.
        Если элемент не появился, бросает timeout exception.

        Args:
            element (Element): Элемент, который ждём
            timeout (int, optional): Таймаут ожидания (сек.), по умолчанию 5.

        Raises:
            TimeoutException

        Examples:
            >>> browser.wait_for_element_visible(Element("#header", 15))

        """
        log_step(f"Wait for element visible {element}")
        self.wait(timeout, poll_frequency).until(visibility_of(element))

    def wait_for_element_not_visible(self, element, timeout=5, poll_frequency=0.5):
        """
        Ждёт до ``timeout`` сек. исчезновения элемента.
        Если элемент остался видимым, бросает timeout exception.

        Args:
            element (Element): Элемент, который ждём
            timeout (int, optional): Таймаут ожидания (сек.), по умолчанию 5.

        Raises:
            TimeoutException

        Examples:
            >>> browser.wait_for_element_not_visible(Element("#header", 15))
        """
        log_step(f"Wait for element not visible {element}")
        self.wait(timeout, poll_frequency).until(invisibility_of(element))

    def see_element(self, element, attributes={}):
        """
        Проверяет, что элемент существует и видим.
        Также можно указать атрибуты этого элемента.

        Args:
            element (Element): Элемент
            attributes (dict, optional): Словарь атрибутов

        Examples:
            >>> browser.see_element(Element("tr"))
            >>> browser.see_element(Element("tr"), {"some-attr": "some-value"})
        """
        log_step(f"See element {element}, {attributes}")
        self._enable_implicit_wait()
        els = self._match_visible(element)
        self._disable_implicit_wait()
        els = self._filter_by_attributes(els, attributes)
        assert_that(els, is_not(empty()))

    def see_text(self, text, element=None):
        """
        Проверяет, что страница содержит текст (с учётом регистра).
        Можно передать элемент, чтобы искать текст только в нём.

        Args:
            text (str): Искомый текст
            element (Element, optional): Элемент

        Examples:
            >>> browser.see_text("Администрирование")
            >>> browser.see_text("Выйти", Element("h1"))
        """
        log_step(f"See text {text} in {element}")
        self._enable_implicit_wait()
        text_from_page = self.grab_visible_text(element)
        self._disable_implicit_wait()
        assert_that(text_from_page, contains_string(text))

    def see_in_field(self, input_element, needle):
        """
        Проверяет, что текст поля ввода равен переданному значению.

        Args:
            input_element (Element): Элемент
            needle (str): Текст

        Examples:
            >>> browser.see_in_field(Element("input#foo"), "Hello World!")
        """
        log_step(f"See text '{needle}' in field {input_element}")
        val = self.grab_value_from(input_element)
        assert_that(val, equal_to(needle))

    def see_number_of_elements(self, element, expected):
        """
        Проверяет, что на странице определённое кол-во элементов.

        Args:
            element (Element): Элемент
            expected (int|tuple): Ожидаемое кол-во

        Returns:
            None

        Raises:
            AssertionError

        Examples:
            >>> browser.see_number_of_elements( E('tr'), 10 )
            >>> browser.see_number_of_elements( E('tr'), (4, 6) ) # Между 4 и 6, включительно
        """
        log_step(f"See number of elements {element}, {expected}")
        count = len(self._match_visible(element))
        if isinstance(expected, tuple):
            a, b = expected
            assert_that(a <= count <= b, is_(True),
                        f'Number of elements expected to be in range {expected}, but was {count}')
        else:
            assert_that(count, equal_to(expected),
                        f'Number of elements expected to be {expected}, but was {count}')

    def grab_visible_text(self, element=None):
        """
        Получает видимый текст всей страницы или элемента.

        Args:
            element (Element, optional): Элемент

        Returns:
            str: Текст

        Examples:
            >>> browser.grab_visible_text()
            >>> browser.grab_visible_text(Element("h1"))
        """
        log_step(f"Get visible text from {element}")
        if element is not None:
            return self.grab_text_from(element)

        els = self._match(Element("body"))
        if len(els) == 0:
            return ''

        return els[0].text

    def click(self, element):
        """
        Кликает по элементу.

        Args:
            element (Element): Элемент

        Examples:
            >>> browser.click(Element("#logout"))
        """
        log_step(f"Click {element}")
        self._match_first_or_fail(element).click()

    def js_click(self, element):
        """
        Click via JS

        Args:
            element (Element)
        """
        log_step(f"Click via JS {element}")
        script = "var rect = arguments[0].getBoundingClientRect();" \
                 "arguments[0].dispatchEvent(new MouseEvent('click', {" \
                 "  'bubbles': true," \
                 "  'cancelable': true," \
                 "  'view': window," \
                 "  'clientX': rect.left + rect.width/2," \
                 "  'clientY': rect.top + rect.height/2" \
                 "}));"
        self.execute_js(script, self._match_first_or_fail(element))

    def grab_visible(self, element):
        """
        Получает видимые элементы.

        Args:
            element (Element, optional): Элемент

        Returns:
            selenium.webdriver.remote.webelement.WebElement[]: Список элементов

        Examples:
            >>> browser.grab_visible(Element("th"))
        """
        log_step(f"Grab visible {element}")
        return self._match_visible(element)

    def grab_text_from(self, element=None):
        """
        Получает текст из переданного элемента
        или из body, если передан None.

        Args:
            element (Element, optional): Элемент

        Returns:
            str: Текст

        Examples:
            >>> browser.grab_text_from(Element("h1"))
        """
        log_step(f"Get text from {element}")
        if element is None:
            element = Element("body")

        el = self._match_first_or_fail(element)
        return el.text

    def js_grab_text_from(self, element):
        log_step(f"Grab text via JS from {element}")
        return self.execute_js("return arguments[0].textContent;", self._match_first_or_fail(element))

    def grab_attribute_from(self, element, attribute):
        """
        Получает значение атрибута.

        Args:
            element     (Element): Элемент
            attribute   (str):  Атрибут

        Returns:
            str: Значение атрибута

        Examples:
            ``<span id="tooltip" title="hello_world"> </span>``

            >>> browser.grab_attribute_from(Element('#tooltip'), 'title')
            "hello_world"
        """
        log_step(f"Grab attribute from {element}")
        el = self._match_first_or_fail(element)
        return el.get_attribute(attribute)

    def grab_value_from(self, input_element):
        """
        Получает value атрибут из поля.
        Используется, чтобы получить введённый текст.

        Args:
            element (Element): Элемент

        Returns:
            str: Значение value атрибута

        Examples:
            ``<input id="login" value="ivanov">``

            >>> browser.grab_value_from(Element('#login'))
            "ivanov"
        """
        log_step(f"Grab value from {input_element}")
        el = self._match_first_or_fail(input_element)
        return el.get_attribute('value')

    def grab_multiple(self, elements):
        """
        Получает тексты подходящих элементов и возващает их как список.

        Args:
            element (Element): Элемент

        Returns:
            str[]: Список текстов

        Examples:
            .. code-block:: html

                <tr> foo </tr>
                <tr> bar </tr>
                <tr> baz </tr>


            >>> browser.grab_multiple( Element('tr') )
            ["foo", "bar", "qaz"]
        """
        log_step(f"Grab multiple {elements}")
        els = self._match(elements)
        return list(map(lambda el: el.text, els))

    def js_grab_multiple(self, element):
        log_step(f"Grab multiple via JS from {element}")
        script = "return Object.values(arguments).map(function(e) { return e.textContent.trim(); });"
        return self.execute_js(script, *self._match(element))

    def save_screenshot(self, name=None):
        """
        Делает скриншот видимой части страницы и сохраняет в ``_output/debug``.

        Args:
            name (str, optional): Имя файла

        Returns:
            pathlib.Path: Путь до файла
        """
        debug_dir = session.output_dir.joinpath('debug')
        if not os.path.exists(debug_dir):
            os.makedirs(debug_dir, exist_ok=True)

        if name is None:
            name = uuid.uuid4()

        file_path = debug_dir.joinpath(f"{name}.png")
        log_step(f"Save screenshot to {file_path}")
        self.get_driver().get_screenshot_as_file(str(file_path))
        return file_path

    def get_screenshot_binary(self):
        """
        Возвращает скриншот в бинарном формате.

        Returns:
            bytes
        """
        log_step(f"Get screenshot as png")
        return self.get_driver().get_screenshot_as_png()

    def move_mouse_over(self, element):
        """
        Передвигает курсор в центр элемента

        Args:
            element (Element): элемент
        """
        log_step(f"Move mouse over {element}")
        el = self._match_first_or_fail(element)
        ActionChains(self.get_driver()).move_to_element(el).perform()

    def switch_to_iframe(self, frame=None):
        """
        Переключяет контекст в iframe.
        Чтобы перейти в родительский фрейм - вызывается без параметров.

        Args:
            frame (Element): iframe

        Examples:
            ``<iframe name="another_frame" src="http://example.com">``

            >>> frame = Element("frame[name = 'another_frame']")
            >>> browser.switch_to_iframe(frame)
            >>> browser.switch_to_iframe() # в родительский фрейм
        """
        log_step(f"Switch to iframe {frame}")
        if frame is not None:
            el = self._match_first_or_fail(frame)
            self.get_driver().switch_to.frame(el)
        else:
            self.get_driver().switch_to.parent_frame()

    def close_window(self):
        """
        Закрывает текущее окно и переключается в предыдущее.

        Returns:
            window handle
        """
        log_step("Close window")
        prev_window = self.get_relative_window_handle(-1)
        self.get_driver().close()
        self.get_driver().switch_to.window(prev_window)
        return prev_window

    def switch_to_next_window(self, offset=1):
        """
        Переключается в следующее окно.

        Args:
            offset (int, optional): По умолчанию 1

        Returns:
            window handle
        """
        log_step("Switching to next window")
        next_window = self.get_relative_window_handle(offset)
        self.get_driver().switch_to.window(next_window)
        return next_window

    def switch_to_prev_window(self, offset=1):
        """
        Переключается в предыдущее окно.

        Args:
            offset (int, optional): По умолчанию 1

        Returns:
            window handle
        """
        log_step("Switching to prev window")
        next_window = self.get_relative_window_handle(0-offset)
        self.get_driver().switch_to.window(next_window)
        return next_window

    def new_window(self, url="about:blank"):
        """
        Открывает новое окно и переключается в него.

        Args:
            url (str, optional): По умолчанию 'about:blank'

        Returns:
            window handle
        """
        log_step(f"Open new window with url '{url}''")
        original_handles = self._driver_instance.window_handles
        self.execute_js(f"window.open('{url}')")
        new_handles = self._driver_instance.window_handles
        new_window_hanle = (set(new_handles) - set(original_handles)).pop()
        self._driver_instance.switch_to.window(new_window_hanle)
        return new_window_hanle

    @contextmanager
    def in_frame(self, frame, exit_to='parent'):
        log_step(f"In frame {frame}")

        if exit_to not in ['parent', 'default']:
            raise TypeError(f"'exit_to' must be 'parent' or 'default', '{exit_to}' given")

        switch = {
            'parent': self.get_driver().switch_to.parent_frame,
            'default': self.get_driver().switch_to.default_content
        }
        try:
            self.switch_to_iframe(frame)
            yield
        finally:
            switch[exit_to]()

    def save_session_snapshot(self, name):
        """
        Сохраняет куки чтобы загрузить их в другом тесте.
        Например, если в каждом тесте необходима авторизация, 
        можно выполнить этот сценарий единожды, 
        а в других тестах только восстанавливать сессию.

        Args:
            name (str): Название сесиии

        Examples:
            >>> def login():
            >>>     # Если сессия существует - пропустить логин
            >>>     if browser.load_session_snapshot("login"):
            >>>         return
            >>>     browser.fill_field( Element("#username") )
            >>>     browser.fill_field( Element("#password") )
            >>>     browser.click( Element("#submit") )
            >>>     browser.save_session_snapshot("login")
        """
        log_step(f"Save session snapshot '{name}'")
        self._session_snapshots[name] = self.get_driver().get_cookies()

    def set_style(self, element, style, value, is_important=True):
        log_step(f"Set style {style}={value} on {element}")
        if is_important:
            script = f"arguments[0].style.setProperty('{style}', '{value}', 'important')"
        else:
            script = f"arguments[0].style.setProperty('{style}', '{value}')"
        self.execute_js(script, self._match_first_or_fail(element))

    def load_session_snapshot(self, name):
        """
        Загружает сохранённую сессию.
        Смотри :func:`~wd.browser.Browser.save_session_snapshot`.

        Args:
            name (str): Имя сессии

        Returns:
            bool
        """
        log_step(f"Load session snapshot '{name}'")
        if name not in self._session_snapshots:
            return False

        for cookie in self._session_snapshots[name]:
            self.set_cookie(cookie["name"], cookie["value"], cookie)

        return True

    def set_cookie(self, name, value, params={}):
        """
        Задаёт куку с именем и значением.
        Можно передать дополнительные параметры.

        Args:
            name    (str): Имя куки
            value   (str): Значение куки
            params  (dict, optional): 
                Доп. параметры:

                    - domain
                    - path
                    - expiry
                    - secure
                    - httpOnly
        """
        log_step(f"Set cookie '{name}': '{value}'")
        params["name"] = name
        params["value"] = value

        if "domain" not in params:
            url_parts = urlparse(SettingsManager.get("url"))
            if "netloc" in url_parts:
                params["domain"] = url_parts["netloc"]

        defaults = {
            "path": '/',
            "expiry": int(time.time()) + 86400,
            "secure": False,
            "httpOnly": False,
        }

        for k, v in defaults.items():
            if k not in params:
                params[k] = v

        self.get_driver().add_cookie(params)

    def scroll_to(self, element, offset_x=0, offset_y=0):
        """
        Скроллит к центру переданного элемента.
        Дополнительное смещение, расчитываемое от левого верхнего угла элемента,
        можно задать параметрами `offset_x` и `offset_y` (в пикселях).

        Важно: вызывает метод scrollTo на объекте window.
        Если элемент находится в каком то контейнере с `overflow: scoll`,
        то данный метод не сработает, см. :func:`~wd.browser.Browser.scroll_into_view`.

        Args:
            element     (Element): элемент
            offset_x    (int, optional): смещение по X (px)
            offset_y    (int, optional): смещение по Y (px)
        """
        log_step(f"Scroll to {element}")
        el = self._match_first_or_fail(element)
        x = el.location['x'] + offset_x
        y = el.location['y'] + offset_y
        self.execute_js(f"window.scrollTo({x}, {y})")

    def scroll_into_view(self, element, scroll_into_view_options={"block": "center"}):
        """
        Скролит страницу к элементу

        Args:
            element (Element): Элемент
            scroll_into_view_options (dict, optional): Параметры, по умолчанию {'block': 'center'}
                https://developer.mozilla.org/ru/docs/Web/API/Element/scrollIntoView
        """
        log_step("Scroll into view")
        el = self._match_first_or_fail(element)
        self.execute_js(f"arguments[0].scrollIntoView({json.dumps(scroll_into_view_options)})", el)

    def delete_all_cookies(self):
        """
        Удаляет все куки.
        """
        log_step("Delete all cookies")
        self.get_driver().delete_all_cookies()

    def dont_see_element(self, element, attributes={}):
        """
        Проверяет, что элемент невидим.

        Args:
            element     (Element): Элемент
            attributes  (dict, optional): Атрибуты

        Raises:
            AssertionError
        """
        log_step(f"Dont see element {element}, {attributes}")
        els = self._match_visible(element)
        els = self._filter_by_attributes(els, attributes)
        assert_that(els, is_(empty()))

    def element_has_attribute(self, element, attr, expected_value=None):
        """
        Проверяет наличие атрибута у элемента.
        Опционально приинимает значение атрибута.

        Args:
            element         (Element): Элемент
            attr            (str): Имя атрибута
            expected_value  (string, optional): Ожидаемое значание

        Returns:
            bool

        Examples:
            ``<div class='foo bar bazqux'> </div>``

            >>> browser.element_has_attribute( Element('div'), 'class' )
            True
            >>> browser.element_has_attribute( Element('div'), 'class', 'foo' )
            True
            >>> browser.element_has_attribute( Element('div'), 'class', 'baz' )
            False
        """
        log_step(f"Element {element} has attribute {attr}: {expected_value}")

        is_attribue_presents = self.execute_js(
            f"return arguments[0].hasAttribute('{attr}');",
            self._match_first_or_fail(element)
        )

        if not is_attribue_presents:
            return False

        if expected_value is None:
            return True
        else:
            actual_val = self.grab_attribute_from(element, attr)

            values_list = re.sub(r'\s+', ' ', actual_val).strip().split(' ')
            if expected_value in values_list:
                return True
            else:
                return False

        # actual_val = self.grab_attribute_from(element, attr)

        # if actual_val is None:
        #     return False
        # elif expected_value is None:
        #     return True
        # else:
        #     values_list = re.sub(r'\s+', ' ', actual_val).strip().split(' ')
        #     if expected_value in values_list:
        #         return True
        #     else:
        #         return False

    def execute_js(self, script, *args):
        """
        Выполняет js на странице.

        Args:
            script  (str): JS скрипт
            *args   (obj): Аргументы

        Returns:
            То, что возвращает скрипт.

        Examples:
            ``<span id="tooltip" data-attr="foo"> </span>``

            >>> script = 'return arguments[0].getAttribute("data-attr");'
            >>> browser.execute_js(script, browser.find(Element("#tooltip")))
            "foo"
        """
        log_step(f"Execute JS '{script}'")
        return self.get_driver().execute_script(script, *args)

    def sleep(self, secs):
        """
        Просто ждёт ``secs`` секунд.

        Args:
            secs (float): Сколько секунд спать

        Raises:
            Exception: Если передали больше 1000 сек.
        """
        log_step(f"Sleep {secs}")
        if secs >= 1000:
            raise Exception("Waiting for more then 1000 seconds: 16.6667 mins")
        time.sleep(secs)

    def wd_wait(self, timeout=10, poll_frequency=0.5):
        """
        Возвращает объект WebDriverWait.

        Args:
            timeout         (int, optional): Таймаут ожидания, по умолчанию 10
            poll_frequency  (float, optional): Частота опроса, по умолчанию 0.5

        Returns:
            WebDriverWait
        """
        return WebDriverWait(self.get_driver(), timeout, poll_frequency)

    def wait(self, timeout=10, poll_frequency=0.5):
        """
        Возвращает объект wasd.support.wait.Wait
        """
        return Wait(self, timeout, poll_frequency)

    def scroll_top(self):
        log_step("Window scroll top")
        self.execute_js("window.scrollTo(0, 0)")

    def get_relative_window_handle(self, offset):
        original_handles = self._driver_instance.window_handles
        this_window = self._driver_instance.current_window_handle
        idx = original_handles.index(this_window)
        next_window = original_handles[(idx+offset) % len(original_handles)]
        return next_window

    def find(self, element):
        context = self.get_driver()
        try:
            if element.ctx is not None:
                context = self.find(element.ctx)

            if isinstance(element, ShadowElement):
                el = context.find_element(*element.locator())
                return self.execute_js('return arguments[0].shadowRoot;', el)
            else:
                return context.find_element(*element.locator())
        except NoSuchElementException as e:
            e.msg = f"No such element: Unable to locate element: {element}"
            raise

    def finds(self, element):
        context = self.get_driver()
        if element.ctx is not None:
            context = self.find(element.ctx)

        return context.find_elements(*element.locator())

    def _filter_by_attributes(self, els, attributes):
        for k, v in attributes.items():
            els = list(filter(
                lambda el: el.get_attribute(k) == v,
                els))
        return els

    def _match_visible(self, element):
        els = self._match(element)
        nodes = list(filter(
            lambda el: el.is_displayed(),
            els))
        return nodes

    def _match_first_or_fail(self, element):
        self._enable_implicit_wait()
        els = self._match(element)
        self._disable_implicit_wait()
        if not els:
            raise Exception("Element {0} was not found.".format(element))
        return els[0]

    def _match(self, element):
        return self.finds(element)

    def _enable_implicit_wait(self):
        self.get_driver().implicitly_wait(SettingsManager.get('implicit_timeout'))

    def _disable_implicit_wait(self):
        self.get_driver().implicitly_wait(0)

    def _convert_key_modifier(self, keys):
        if not isinstance(keys, tuple):
            return (keys,)
        if keys[0] in ["ctrl", "contol"]:
            return (Keys.CONTROL, keys[1])
        if keys[0] == "alt":
            return (Keys.ALT, keys[1])
        if keys[0] == "shift":
            return (Keys.SHIFT, keys[1])
        if keys[0] == "meta":
            return (Keys.META, keys[1])
        return keys
コード例 #44
0
    def setUp(self):
        self.driver = EventFiringWebDriver(webdriver.Chrome(), MyListener())
        driver = self.driver

        run = nf.setUp_func(driver, server)
コード例 #45
0
from selenium import webdriver
from selenium.webdriver.support.events import EventFiringWebDriver
from webevent_listeners.MyListeners import MyListeners

driver = webdriver.Chrome()
eDriver = EventFiringWebDriver(driver, MyListeners())
eDriver.implicitly_wait(30)
eDriver.maximize_window()
eDriver.get("https://www.seleniumhq.org/download/")

eDriver.find_element_by_xpath(
    "//span[contains(text(),'Safety Features')]").click()

eDriver.close()
コード例 #46
0
 def setUp(self):
     self.driver = super().run_driver()
     self.driver = EventFiringWebDriver(
         self.driver, ScreenshotListener(self._testMethodName))
コード例 #47
0
 def test_should_unwrap_element_args_when_switching_frames(self):
     ef_driver = EventFiringWebDriver(self.driver, AbstractEventListener())
     ef_driver.get(self._pageURL("iframes"))
     frame = ef_driver.find_element_by_id("iframe1")
     ef_driver.switch_to.frame(frame)
     self.assertEqual("click me!", ef_driver.find_element_by_id("imageButton").get_attribute("alt"))
コード例 #48
0
    def after_click(self, element, webdriver):
        nome = webdriver.find_element_by_id("lnome").text
        email = webdriver.find_element_by_id("lemail").text
        senha = webdriver.find_element_by_id("lsenha").text

        if nome != "nome:":
            nome_text.append(nome)

        if email != "email:":
            email_text.append(email)

        if senha != "senha:":
            senha_text.append(senha)


wraperBroswer = EventFiringWebDriver(driver, Escutando())
wraperBroswer.get(url)

sleep(4)
nome = wraperBroswer.find_element_by_id("nome")
nome.send_keys("Alison")
nome.click()

email = wraperBroswer.find_element_by_id("email")
email.send_keys("*****@*****.**")
email.click()

senha = wraperBroswer.find_element_by_id("senha")
senha.send_keys("123456")
senha.click()
コード例 #49
0
##event finding c#
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener


class MyListener(AbstractEventListener):
    def before_find(self, by, value, driver):
        print(by, value)

    def after_find(self, by, value, driver):
        print(by, value, "found")

    def on_exception(self, exception, driver):
        print(exception)


wd = EventFiringWebDriver(webdriver.Chrome(), MyListener())
####################################################################

#get screenshoot
driver.get_screenshot_as_file('screen.png')
####################################################################

#get browser logs
for l in driver.get_log("browser"):
    print(l)
####################################################################

#proxy traffic
driver = webdriver.Chrome(desired_capabilities={
    "proxy": {
        "proxyType": "MANUAL",
コード例 #50
0
ファイル: task17.py プロジェクト: Nechuparniy/selenium
def driver(request):
    # wd = webdriver.Chrome()
    wd = EventFiringWebDriver(webdriver.Chrome(), MyListener())
    # wd.implicitly_wait(10)
    request.addfinalizer(wd.quit)
    return wd
コード例 #51
0
 def setup_method(self, method):
     self.driver = EventFiringWebDriver(remote_webdriver, MaListener())
     self.current_method_name = method.__name__
コード例 #52
0
ファイル: surfer.py プロジェクト: rotsee/SDRSkrejper
class Surfer:
    """This class does virtual web surfing on our demand
    """

    def __init__(self, delay=1, browser="firefox"):
        """delay: Number of extra seconds to wait when a page is
           supposedly loaded. Try raising this in case of weird errors.

           browser: `firefox` or `chrome`. The ChromeDriver executable for your
           OS must be inside the bin directory for Chrome to work. Get it from:
           http://chromedriver.storage.googleapis.com/index.html
        """
        self.extra_delay = delay  # extra time to wait after each operation (s)
        self.temp_dir = mkdtemp()

        self.vdisplay = Xvfb()
        self.vdisplay.start()
        if browser == "firefox":
            profile = FirefoxProfile()
            # Open links in same window
            profile.set_preference("browser.link.open_newwindow", 1)
            # Download to temp dir, for files we can't open inline
            profile.set_preference("browser.download.dir", self.temp_dir)
            profile.set_preference("browser.download.folderList", 2)
            profile.set_preference("browser.download.manager.showWhenStarting",
                                   "False")
            profile.set_preference("browser.helperApps.neverAsk.saveToDisk",
                                   "application/msword, application/vnd.ms-word, application/rtf, application/octet-stream")

            # Add extension for overriding Content-Disposition headers, etc
            extensions_dir = os_sep.join(['bin', 'firefox-plugins-enabled'])
            for filename in listdir(extensions_dir):
                fullfilename = os_sep.join([extensions_dir, filename])
                profile.add_extension(extension=fullfilename)

            driver = Firefox(profile)
        elif browser == "chrome":
            # Add extension for overriding Content-Disposition headers
            options = ChromeOptions()
            options.add_extension('bin/undisposition.crx')
            driver = Chrome(executable_path='bin/chromedriver',
                            chrome_options=options)
        else:
            raise Exception("Not a valid browser name")

        self.selenium_driver = EventFiringWebDriver(driver, CustomListener())
        """selenium_driver is a EventFiringWebDriver, so that it can
           trigger javascript event
        """
        self.browser_version = " ".join([
            self.selenium_driver.capabilities['browserName'],
            self.selenium_driver.capabilities['version']])  # 'Firefox 33.0'

    def get_last_download(self):
        files = sorted([
            f for f in listdir(self.temp_dir)])
        if len(files) > 0:
            return self.temp_dir + os_sep + files[-1]
        else:
            return None

    def _get_nearest_ancestor(self, element, tagname):
        ancestor = element.find_element_by_xpath("..")
        while ancestor is not None and ancestor.tag_name != tagname:
            try:
                ancestor = element.find_element_by_xpath("..")
            except InvalidSelectorException:
                ancestor = None
        return ancestor

    def _scroll_element_into_view(self, element):
        """Scroll attached element into view
        """
        y = element.location['y']
        self.selenium_driver.execute_script('window.scrollTo(0, {0})'
                                            .format(y))

    def with_open_in_new_window(self, element, callback_, *args, **kwargs):
        """Shift-clicks on an element to open a new window,
           calls the callback function, and then closes the
           window and returns.
           This is useful for iterating through a link tree
           we cannot easily step back in (e.g. where the starting
           the result of a POST request)

           Callback function is called like this: `callback(Surfer, arguments)`
           with a Surfer object placed in the new window

           Returns the result of `callback`
        """
        try:
            actions = ActionChains(self.selenium_driver)
            actions.move_to_element(element).perform()
            self._scroll_element_into_view(element)
            element.send_keys(Keys.SHIFT + Keys.ENTER)
        except ElementNotVisibleException:
            raise
        self.selenium_driver.implicitly_wait(self.extra_delay)
        sleep(self.extra_delay)  # implicitly_wait doesn't work on FF?
        windows = self.selenium_driver.window_handles
        self.selenium_driver.switch_to_window(windows[-1])
        if len(windows) > 1:
            res = callback_(self, *args, **kwargs)
            self.selenium_driver.close()
        windows = self.selenium_driver.window_handles
        self.selenium_driver.switch_to_window(windows[-1])
        return res

    def surf_to(self, url):
        """Simply go to an URL"""
        try:
            self.selenium_driver.get(url)
        except TimeoutException:
            raise ConnectionError
        self.selenium_driver.implicitly_wait(self.extra_delay)

    def click_on_stuff(self, xpath):
        """Will click on any elements pointed out by xPath.

           Options in select menus will be selected, and an
           onChange event fired (as this does not always happen automatically)
        """
        # FIXME: Select menus will only work if they have an id!
        element_list = self.selenium_driver.find_elements_by_xpath(xpath)
        if not element_list:
            raise Exception("No elements found for xPath `%s`" % xpath)
        else:
            for element in element_list:
                try:
                    element.click()
                except ElementNotVisibleException:
                    # Element not visible. This is not necessarily an error.
                    # but the user might want to consider using a more
                    # specific xPath expression.
                    continue
#                actions = ActionChains(self.selenium_driver)
#                actions.move_to_element(element)
#                actions.click(element)
#                actions.send_keys_to_element(element, Keys.ENTER)
#                actions.perform()
                if "tag_name" in dir(element) and element.tag_name == "option":
                    parent = self._get_nearest_ancestor(element, "select")
                    if parent is not None:
                        # Should be selected already, when clicking,
                        # but it seems like this does not always happen
                        value = element.get_attribute("value") or None
                        if value is not None:
                            select = Select(parent)
                            select.select_by_value(value)
                        # Manually trigger JS events
                        select_id = parent.get_attribute("id") or None
                        if select_id is not None:
                            js_function = """
    window.triggerChange=function(){\
        var el = document.getElementById('""" + select_id + """');\
        el.dispatchEvent(new Event('change', { 'bubbles': true }));\
        el.dispatchEvent(new Event('select', { 'bubbles': true }));\
        el.dispatchEvent(new Event('click', { 'bubbles': true }));\
    };"""
                            self.selenium_driver.execute_script(js_function)
                            self.selenium_driver.execute_script("triggerChange();")
                    else:
                        raise Exception("No <select> tag found for <option>")
            self.selenium_driver.implicitly_wait(self.extra_delay)

    def get_url_list(self, xpath):
        url_list = []
        element_list = self.selenium_driver.find_elements_by_xpath(xpath)
        for element in element_list:
            href = element.get_attribute("href")
            if href is not None:
                url_list.append(Url(href))
        return url_list  # list of Url objects

    def get_element_list(self, xpath):
        try:
            return self.selenium_driver.find_elements_by_xpath(xpath)
        except InvalidSelectorException:
            pass
        # maybe our xPath points at an attribute?
        try:
            return self.selenium_driver.find_elements_by_xpath(xpath + "/..")
        except InvalidSelectorException:
            pass
        return None

    def kill(self):
        self.selenium_driver.close()
        self.vdisplay.stop()
        rmtree(self.temp_dir)
コード例 #53
0
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener


class MyListener(AbstractEventListener):
    def before_navigate_to(self, url, driver):
        print("Log: Before navigate to {}".format(url))

    def after_navigate_to(self, url, driver):
        print("Log: After navigate to {}".format(url))


driver = webdriver.Chrome()
ef_driver = EventFiringWebDriver(driver, MyListener())
ef_driver.get("http://python.org")
driver.close()
コード例 #54
0
ファイル: surfer.py プロジェクト: rotsee/protokollen
class Surfer:
    """This class does virtual web surfing on our demand
    """
    def __init__(self, delay=1, browser="firefox"):
        """delay: Number of extra seconds to wait when a page is
           supposedly loaded. Try raising this in case of weird errors.

           browser: `firefox` or `chrome`. The ChromeDriver executable for your
           OS must be inside the bin directory for Chrome to work. Get it from:
           http://chromedriver.storage.googleapis.com/index.html
        """
        self.extra_delay = delay  # extra time to wait after each operation (s)
        self.temp_dir = mkdtemp()

        self.vdisplay = Xvfb()
        self.vdisplay.start()

        def get_bin_path(subdir):
            path = os_path.dirname(os_path.realpath(__file__)) + os_sep
            return path + os_sep.join([pardir, "bin", subdir])

        if browser == "firefox":
            profile = FirefoxProfile()
            # Open links in same window
            profile.set_preference("browser.link.open_newwindow", 1)
            # Download to temp dir, for files we can't open inline
            profile.set_preference("browser.download.dir", self.temp_dir)
            profile.set_preference("browser.download.folderList", 2)
            profile.set_preference("browser.download.manager.showWhenStarting",
                                   "False")
            profile.set_preference(
                "browser.helperApps.neverAsk.saveToDisk",
                "application/msword, application/vnd.ms-word, application/rtf, application/octet-stream"
            )

            # Add extension for overriding Content-Disposition headers, etc
            extensions_dir = get_bin_path('firefox-plugins-enabled')
            for filename in listdir(extensions_dir):
                fullfilename = os_sep.join([extensions_dir, filename])
                profile.add_extension(extension=fullfilename)

            driver = Firefox(profile)
        elif browser == "chrome":
            # Add extension for overriding Content-Disposition headers
            options = ChromeOptions()
            options.add_extension(get_bin_path('bin/undisposition.crx'))
            driver = Chrome(executable_path=get_bin_path('bin/chromedriver'),
                            chrome_options=options)
        else:
            raise Exception("Not a valid browser name")

        self.selenium_driver = EventFiringWebDriver(driver, CustomListener())
        """selenium_driver is a EventFiringWebDriver, so that it can
           trigger javascript event
        """
        self.browser_version = " ".join([
            self.selenium_driver.capabilities['browserName'],
            self.selenium_driver.capabilities['version']
        ])  # 'Firefox 33.0'

    def get_last_download(self):
        files = sorted([f for f in listdir(self.temp_dir)])
        if len(files) > 0:
            return self.temp_dir + os_sep + files[-1]
        else:
            return None

    def _get_nearest_ancestor(self, element, tagname):
        ancestor = element.find_element_by_xpath("..")
        while ancestor is not None and ancestor.tag_name != tagname:
            try:
                ancestor = element.find_element_by_xpath("..")
            except InvalidSelectorException:
                ancestor = None
        return ancestor

    def _scroll_element_into_view(self, element):
        """Scroll attached element into view
        """
        y = element.location['y']
        self.selenium_driver.execute_script(
            'window.scrollTo(0, {0})'.format(y))

    def with_open_in_new_window(self, element, callback_, *args, **kwargs):
        """Shift-clicks on an element to open a new window,
           calls the callback function, and then closes the
           window and returns.
           This is useful for iterating through a link tree
           we cannot easily step back in (e.g. where the starting
           the result of a POST request)

           Callback function is called like this: `callback(Surfer, arguments)`
           with a Surfer object placed in the new window

           Returns the result of `callback`
        """
        try:
            actions = ActionChains(self.selenium_driver)
            actions.move_to_element(element).perform()
            self._scroll_element_into_view(element)
            element.send_keys(Keys.SHIFT + Keys.ENTER)
        except ElementNotVisibleException:
            raise
        self.selenium_driver.implicitly_wait(self.extra_delay)
        sleep(self.extra_delay)  # implicitly_wait doesn't work on FF?
        windows = self.selenium_driver.window_handles
        self.selenium_driver.switch_to_window(windows[-1])
        if len(windows) > 1:
            res = callback_(self, *args, **kwargs)
            self.selenium_driver.close()
            windows = self.selenium_driver.window_handles
            self.selenium_driver.switch_to_window(windows[-1])
            return res
        else:
            return None

    def surf_to(self, url):
        """Simply go to an URL"""
        try:
            self.selenium_driver.get(url)
        except TimeoutException:
            raise ConnectionError
        except BadStatusLine:
            raise ConnectionError
        self.selenium_driver.implicitly_wait(self.extra_delay)

    def click_on_stuff(self, xpath):
        """Will click on any elements pointed out by xPath.

           Options in select menus will be selected, and an
           onChange event fired (as this does not always happen automatically)
        """
        # FIXME: Select menus will only work if they have an id!
        element_list = self.selenium_driver.find_elements_by_xpath(xpath)
        if not element_list:
            raise Exception("No elements found for xPath `%s`" % xpath)
        else:
            for element in element_list:
                try:
                    element.click()
                except ElementNotVisibleException:
                    # Element not visible. This is not necessarily an error.
                    # but the user might want to consider using a more
                    # specific xPath expression.
                    continue


#                actions = ActionChains(self.selenium_driver)
#                actions.move_to_element(element)
#                actions.click(element)
#                actions.send_keys_to_element(element, Keys.ENTER)
#                actions.perform()
                if "tag_name" in dir(element) and element.tag_name == "option":
                    parent = self._get_nearest_ancestor(element, "select")
                    if parent is not None:
                        # Should be selected already, when clicking,
                        # but it seems like this does not always happen
                        value = element.get_attribute("value") or None
                        if value is not None:
                            select = Select(parent)
                            select.select_by_value(value)
                        # Manually trigger JS events
                        select_id = parent.get_attribute("id") or None
                        if select_id is not None:
                            js_function = """
    window.triggerChange=function(){\
        var el = document.getElementById('""" + select_id + """');\
        el.dispatchEvent(new Event('change', { 'bubbles': true }));\
        el.dispatchEvent(new Event('select', { 'bubbles': true }));\
        el.dispatchEvent(new Event('click', { 'bubbles': true }));\
    };"""
                            self.selenium_driver.execute_script(js_function)
                            self.selenium_driver.execute_script(
                                "triggerChange();")
                    else:
                        raise Exception("No <select> tag found for <option>")
            self.selenium_driver.implicitly_wait(self.extra_delay)

    def get_url_list(self, xpath):
        url_list = []
        element_list = self.selenium_driver.find_elements_by_xpath(xpath)
        for element in element_list:
            href = element.get_attribute("href")
            if href is not None:
                url_list.append(Url(href))
        return url_list  # list of Url objects

    def get_element_list(self, xpath):
        try:
            return self.selenium_driver.find_elements_by_xpath(xpath)
        except InvalidSelectorException:
            pass
        # maybe our xPath points at an attribute?
        try:
            return self.selenium_driver.find_elements_by_xpath(xpath + "/..")
        except InvalidSelectorException:
            pass
        return None

    def kill(self):
        self.selenium_driver.close()
        self.vdisplay.stop()
        rmtree(self.temp_dir)
コード例 #55
0
ファイル: BaseTest.py プロジェクト: jjaros587/automated_tests
 def setUp(self):
     self.driver = super().run_driver()
     self.driver = EventFiringWebDriver(
         self.driver, ScreenshotListener(self._testMethodName))
     LoginPage(self.driver).login_as_super_admin()
コード例 #56
0
        print(f'antes do click no {elemento.tag_name}')
    def after_click(self, elemento, webdriver):
        if elemento.tag_name == 'label':
            print(webdriver.find_element_by_tag_name('label').text)
        print(f'depois do click no {elemento.tag_name}')

def preencher_form(browser, id, valor, id_label):
    this_id = f'input[id="{id}"'
    this_id_label = f'label[id="{id_label}"'
    input_nome = browser.find_element_by_css_selector(this_id)
    input_nome.send_keys(valor)
    sleep(1)
    label = browser.find_element_by_css_selector(this_id_label)
    label.click()

browser = Firefox()

rapi_browser = EventFiringWebDriver(browser, Escuta())

rapi_browser.get('https://selenium.dunossauro.live/exercicio_07')

sleep(1)
preencher_form(rapi_browser, 'nome', 'Matheus', 'lnome')
preencher_form(rapi_browser, 'email', '*****@*****.**', 'lemail')
preencher_form(rapi_browser, 'senha', '23456', 'lsenha')

button = browser.find_element_by_css_selector('input[id="btn"]')
button.click()

#browser.quit()