Python selenium.webdriver.support.ui.WebDriverWait() Examples

The following are 30 code examples of selenium.webdriver.support.ui.WebDriverWait(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module selenium.webdriver.support.ui , or try the search function .
Example #1
Source File: base.py    From syncPlaylist with MIT License 8 votes vote down vote up
def __init__(self):
        self.browse = None
        self.source_playlist = None
        self.target_playlist_tag = None
        self.success_list = list()
        self.failed_list = list()
        os.environ["webdriver.chrome.driver"] = chrome_driver_path
        os.environ["webdriver.phantomjs.driver"] = phantomjs_driver_path
        # chromedriver = chrome_driver_path
        phantomjs_driver = phantomjs_driver_path

        opts = Options()
        opts.add_argument("user-agent={}".format(headers["User-Agent"]))
        # browser = webdriver.Chrome(chromedriver)
        browser = webdriver.PhantomJS(phantomjs_driver)
        self.browser = browser
        self.wait = ui.WebDriverWait(self.browser, 5)
        self.config = Config() 
Example #2
Source File: driver_utils.py    From toolium with Apache License 2.0 7 votes vote down vote up
def _wait_until(self, condition_method, condition_input, timeout=None):
        """
        Common method to wait until condition met

        :param condition_method: method to check the condition
        :param condition_input: parameter that will be passed to the condition method
        :param timeout: max time to wait
        :returns: condition method response
        """
        # Remove implicitly wait timeout
        implicitly_wait = self.get_implicitly_wait()
        if implicitly_wait != 0:
            self.driver_wrapper.driver.implicitly_wait(0)
        try:
            # Get explicitly wait timeout
            timeout = timeout if timeout else self.get_explicitly_wait()
            # Wait for condition
            condition_response = WebDriverWait(self.driver_wrapper.driver, timeout).until(
                lambda s: condition_method(condition_input))
        finally:
            # Restore implicitly wait timeout from properties
            if implicitly_wait != 0:
                self.set_implicitly_wait()
        return condition_response 
Example #3
Source File: __init__.py    From bilibiliupload with MIT License 7 votes vote down vote up
def crack(self):
        true_image = self.get_true_image()
        x_offset = self.analysis(true_image)
        print(x_offset)

        track = self.get_track(x_offset)
        knob_element = WebDriverWait(self.driver, 50).until(
            EC.element_to_be_clickable((By.XPATH, r'/html/body/div[2]/div[2]/div[6]/div/div[1]/div[2]/div[2]')))
        self.move_to_gap(knob_element, track)

        # fn = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'result0.png')
        # fn1 = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'result1.png')
        # time.sleep(0.02)
        # screen_shot = self.driver.save_screenshot(fn)
        # time.sleep(2)
        # screen_shot = self.driver.save_screenshot(fn1) 
Example #4
Source File: TraTicketBooker.py    From TRA-Ticket-Booker with GNU General Public License v3.0 7 votes vote down vote up
def submit_user_data(self):
        # Submit to Authent-Number Page (press button).
        wait = WebDriverWait(self.driver, timeout=6)
        try:
            self.driver.execute_script(
                'document.getElementsByTagName("button")[0].click()'
            )
            wait.until(
                EC.presence_of_element_located(
                    (By.ID, 'idRandomPic')
                )
            )
        except:
            self.label_show_result.setText(
                '【連線逾時或是網路不穩定】\n' + 
                '【請檢查網路環境以及是否為尖峰時段。】'
            ) 
Example #5
Source File: crawler_cei.py    From ir with Mozilla Public License 2.0 7 votes vote down vote up
def __login(self):
        if self.debug: self.driver.save_screenshot(self.directory + r'01.png')
        txt_login = self.driver.find_element_by_id('ctl00_ContentPlaceHolder1_txtLogin')
        txt_login.clear()
        txt_login.send_keys(os.environ['CPF'])

        time.sleep(3.0)
        txt_senha = self.driver.find_element_by_id('ctl00_ContentPlaceHolder1_txtSenha')
        txt_senha.clear()
        txt_senha.send_keys(os.environ['SENHA_CEI'])
        time.sleep(3.0)

        if self.debug: self.driver.save_screenshot(self.directory + r'02.png')

        btn_logar = self.driver.find_element_by_id('ctl00_ContentPlaceHolder1_btnLogar')
        btn_logar.click()

        try:
            WebDriverWait(self.driver, 60).until(EC.visibility_of_element_located((By.ID, 'objGrafPosiInv')))
        except Exception as ex:
            raise Exception('Nao foi possivel logar no CEI. Possivelmente usuario/senha errada ou indisponibilidade do site')

        if self.debug: self.driver.save_screenshot(self.directory + r'03.png') 
Example #6
Source File: main.py    From uncaptcha with MIT License 7 votes vote down vote up
def click_tiles(driver, coords):
    orig_srcs, new_srcs = {}, {}
    for (x, y) in coords:
        logging.debug("[*] Going to click {} {}".format(x,y))
        tile1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@id="rc-imageselect-target"]/table/tbody/tr[{0}]/td[{1}]'.format(x, y))))
        orig_srcs[(x, y)] = driver.find_element(By.XPATH, "//*[@id=\"rc-imageselect-target\"]/table/tbody/tr[{}]/td[{}]/div/div[1]/img".format(x,y)).get_attribute("src")
        new_srcs[(x, y)] = orig_srcs[(x, y)] # to check if image has changed 
        tile1.click()
        wait_between(0.1, 0.5)

    logging.debug("[*] Downloading new inbound image...")
    new_files = {}
    for (x, y) in orig_srcs:
        while new_srcs[(x, y)] == orig_srcs[(x, y)]:
            new_srcs[(x, y)] = driver.find_element(By.XPATH, "//*[@id=\"rc-imageselect-target\"]/table/tbody/tr[{}]/td[{}]/div/div[1]/img".format(x,y)).get_attribute("src")
            time.sleep(0.5)
        urllib.urlretrieve(new_srcs[(x, y)], "captcha.jpeg")
        new_path = TASK_PATH+"/new_output{}{}.jpeg".format(x, y)
        os.system("mv captcha.jpeg "+new_path)
        new_files[(x, y)] = (new_path)
    return new_files 
Example #7
Source File: ConnectionScraper.py    From scrape-linkedin-selenium with MIT License 6 votes vote down vote up
def get_first_connections(self):
        try:
            see_connections_link = WebDriverWait(self.driver, self.timeout).until(EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '.pv-top-card-v2-section__link--connections'
            )))
        except TimeoutException as e:
            print("""Took too long to load connections link. This usually indicates you were trying to
scrape the connections of someone you aren't connected to.""")
            return []

        see_connections_link.click()
        try:
            self.configure_connection_type()
        except TimeoutException:
            return []
        all_conns = [] 
Example #8
Source File: publish_modules.py    From maintainer-tools with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(driver, user, password):
    wait = WebDriverWait(driver, 10)
    driver.get(
        'https://www.odoo.com/web/login?redirect=%2Foauth2%2Fauth%2F%3Fscope'
        '%3Duserinfo%26redirect_uri%3Dhttps%253A%252F%252Fapps.odoo.com%252F'
        'auth_oauth%252Fsignin%26state%3D%257B%2522p%2522%253A%2B1%252C%2B'
        '%2522r%2522%253A%2B%2522%25252F%25252Fapps.odoo.com%25252Fapps%25'
        '22%252C%2B%2522d%2522%253A%2B%2522apps%2522%257D%26response_type%3D'
        'token%26client_id%3Da0a30d16-6095-11e2-9c70-002590a17fd8&scope=user'
        'info&mode=login&redirect_hostname=https%3A%2F%2Fapps.odoo.com&login='
    )
    login_field = driver.find_element_by_id('login')
    login_field.clear()
    login_field.send_keys(user)
    password_field = driver.find_element_by_id('password')
    password_field.clear()
    password_field.send_keys(password)
    login_button = driver.find_element_by_xpath(
        './/form[@action="/web/login"]//button[@type="submit"]'
    )
    login_button.click()
    wait.until(
        lambda driver: driver.current_url == 'https://apps.odoo.com/apps'
    ) 
Example #9
Source File: test_helper.py    From python-client with Apache License 2.0 6 votes vote down vote up
def wait_for_element(driver: 'WebDriver', locator: str, value: str, timeout: int = SLEEPY_TIME) -> 'WebElement':
    """Wait until the element located

    Args:
        driver: WebDriver instance
        locator: Locator like WebDriver, Mobile JSON Wire Protocol
            (e.g. `appium.webdriver.common.mobileby.MobileBy.ACCESSIBILITY_ID`)
        value: Query value to locator
        timeout: Maximum time to wait the element. If time is over, `TimeoutException` is thrown

    Raises:
        `selenium.common.exceptions.TimeoutException`

    Returns:
        The found WebElement
    """
    return WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((locator, value))
    ) 
Example #10
Source File: bots.py    From Dallinger with MIT License 6 votes vote down vote up
def sign_off(self):
        """Submit questionnaire and finish.

        This uses Selenium to click the submit button on the questionnaire
        and return to the original window.
        """
        try:
            logger.info("Bot player signing off.")
            feedback = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.ID, "submit-questionnaire"))
            )
            self.complete_questionnaire()
            feedback.click()
            logger.info("Clicked submit questionnaire button.")
            self.driver.switch_to_window(self.driver.window_handles[0])
            self.driver.set_window_size(1024, 768)
            logger.info("Switched back to initial window.")
            return True
        except TimeoutException:
            logger.error("Error during experiment sign off.")
            return False 
Example #11
Source File: pytest_dallinger.py    From Dallinger with MIT License 6 votes vote down vote up
def wait_for_text(driver, el_id, value, removed=False, timeout=10):
    el = wait_for_element(driver, el_id, timeout)
    if value in el.text and not removed:
        return el
    if removed and value not in el.text:
        return el

    wait = WebDriverWait(driver, timeout)
    condition = EC.text_to_be_present_in_element((By.ID, el_id), value)
    if removed:
        wait.until_not(condition)
        if value not in el.text:
            return el
    else:
        wait.until(condition)
        if value in el.text:
            return el

    raise AttributeError 
Example #12
Source File: readcomic.py    From ReadComicOnline-Downloader with MIT License 6 votes vote down vote up
def Single_Issue(url,Quality):
	#print url
	print 'Quality To Download : ',Quality[0]
	print 'Order To Download : ',Quality[1]
	#sys.exit()
	#print url,' This is first'
	
	browser = webdriver.PhantomJS(service_args=['--load-images=no'])
	browser.get(url)
	try:
		element = WebDriverWait(browser, 10).until(
			EC.presence_of_element_located((By.ID, "stSegmentFrame"))
		)
		#print 'Downloading the whole page! Will take some time, please don\'t close this script...\n'
		#print 'I\'ve waited long enough'
	except Exception, e:
		#raise e
		browser.save_screenshot('Single_exception.png')
		print e
		pass 
Example #13
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def get_last_seen(self, name, timeout=10):
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)  # we will send the name to the input key box
        last_seen_css_selector = "._315-i"
        start_time = dt.datetime.now()
        try:
            WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.CSS_SELECTOR, last_seen_css_selector)))
            while True:
                last_seen = self.browser.find_element_by_css_selector(last_seen_css_selector).text
                if last_seen and "click here" not in last_seen:
                    return last_seen
                end_time = dt.datetime.now()
                elapsed_time = (end_time-start_time).seconds
                if elapsed_time > 10:
                    return "None"
        except TimeoutException:
            raise TimeoutError("Your request has been timed out! Try overriding timeout!")
        except NoSuchElementException:
            return "None"
        except Exception:
            return "None"

    # This method does not care about anything, it sends message to the currently active chat
    # you can use this method to recursively send the messages to the same person 
Example #14
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def send_blind_message(self, message):
        try:
            message = self.emojify(message)
            send_msg = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]")))
            messages = message.split("\n")
            for msg in messages:
                send_msg.send_keys(msg)
                send_msg.send_keys(Keys.SHIFT+Keys.ENTER)
            send_msg.send_keys(Keys.ENTER)
            return True
        except NoSuchElementException:
            return "Unable to Locate the element"
        except Exception as e:
            print(e)
            return False

    # This method will send you the picture 
Example #15
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def clear_chat(self, name):
        self.browser.find_element_by_css_selector("._3FRCZ").send_keys(name+Keys.ENTER)
        menu_xpath = "/html/body/div[1]/div/div/div[4]/div/header/div[3]/div/div[3]/div/span"
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, menu_xpath)))
        menu = self.browser.find_element_by_xpath(menu_xpath)
        menu.click()
        chains = ActionChains(self.browser)
        for i in range(4):
            chains.send_keys(Keys.ARROW_DOWN)
        chains.send_keys(Keys.ENTER)
        chains.perform()
        clear_xpath = '//*[@id="app"]/div/span[2]/div/div/div/div/div/div/div[2]/div[2]'
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, clear_xpath)))
        self.browser.find_element_by_xpath(clear_xpath).click()



    # override the timeout 
Example #16
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def get_profile_pic(self, name):
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)
        try:
            open_profile = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div[1]/div/div/div[3]/div/header/div[1]/div/img")))
            open_profile.click()
        except:
            print("nothing found")
        try:
            open_pic =  WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div[1]/div/div/div[1]/div[3]/span/div/span/div/div/div/div[1]/div[1]/div/img")))
            open_pic.click()
        except:
            print("Nothing found")
        try:
            img = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                    (By.XPATH,'//*[@id="app"]/div/span[2]/div/div/div[2]/div/div/div/div/img')))
        except:
            print("Couldn't find the URL to the image")
        img_src_url = img.get_attribute('src')
        self.browser.get(img_src_url)
        self.browser.save_screenshot(name+"_img.png") 
Example #17
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def send_anon_message(self, phone, text):
        payload = urlencode({"phone": phone, "text": text, "source": "", "data": ""})
        self.browser.get("https://api.whatsapp.com/send?"+payload)
        try:
            Alert(self.browser).accept()
        except:
            print("No alert Found")
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#action-button")))
        send_message = self.browser.find_element_by_css_selector("#action-button")
        send_message.click()
        confirm = WebDriverWait(self.browser, self.timeout+5).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]")))
        confirm.clear()
        confirm.send_keys(text+Keys.ENTER)

    # Check if the message is present in an user chat 
Example #18
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 6 votes vote down vote up
def __init__(self, wait, screenshot=None, session=None):
        chrome_options = Options()
        if session:
            chrome_options.add_argument("--user-data-dir={}".format(session))
            self.browser = webdriver.Chrome(options=chrome_options)  # we are using chrome as our webbrowser
        else:
            self.browser = webdriver.Chrome()
        self.browser.get("https://web.whatsapp.com/")
        # emoji.json is a json file which contains all the emojis
        with open("emoji.json") as emojies:
            self.emoji = json.load(emojies)  # This will load the emojies present in the json file into the dict
        WebDriverWait(self.browser,wait).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, '._3FRCZ')))
        if screenshot is not None:
            self.browser.save_screenshot(screenshot)  # This will save the screenshot to the specified file location

    # This method is used to send the message to the individual person or a group
    # will return true if the message has been sent, false else 
Example #19
Source File: CompanyScraper.py    From scrape-linkedin-selenium with MIT License 6 votes vote down vote up
def load_initial(self, company):
        url = 'https://www.linkedin.com/company/{}'.format(company)

        self.driver.get(url)
        try:
            myElem = WebDriverWait(self.driver, self.timeout).until(AnyEC(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '.organization-outlet')),
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, '.error-container'))
            ))
        except TimeoutException as e:
            raise ValueError(
                """Took too long to load company.  Common problems/solutions:
                1. Invalid LI_AT value: ensure that yours is correct (they
                   update frequently)
                2. Slow Internet: increase the timeout parameter in the Scraper constructor""")
        try:
            self.driver.find_element_by_css_selector('.organization-outlet')
        except:
            raise ValueError(
                'Company Unavailable: Company link does not match any companies on LinkedIn') 
Example #20
Source File: tests.py    From niji with MIT License 6 votes vote down vote up
def test_stick_to_top_admin(self):
        self.browser.get(self.live_server_url + reverse("niji:index"))
        login(self.browser, 'super', '123')
        self.assertIn("Log out", self.browser.page_source)

        lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50))

        self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={"pk": lucky_topic1.pk}))
        self.browser.find_element_by_class_name('move-topic-up').click()
        up_level = WebDriverWait(
            self.browser, 10
        ).until(
            expected_conditions.presence_of_element_located(
                (By.NAME, 'move-topic-up-level')
            )
        )
        up_level = Select(up_level)
        up_level.select_by_visible_text('1')
        time.sleep(1)
        self.browser.execute_script("$('.modal-confirm').click()")
        self.browser.get(self.live_server_url+reverse('niji:index'))
        first_topic_title = self.browser.find_elements_by_class_name('entry-link')[0].text

        self.assertEqual(first_topic_title, lucky_topic1.title) 
Example #21
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 5 votes vote down vote up
def send_message(self, name, message):
        message = self.emojify(message)  # this will emojify all the emoji which is present as the text in string
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(name+Keys.ENTER)  # we will send the name to the input key box
        try:
            send_msg = WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
                (By.XPATH, "/html/body/div/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]")))
            messages = message.split("\n")
            for msg in messages:
                send_msg.send_keys(msg)
                send_msg.send_keys(Keys.SHIFT+Keys.ENTER)
            send_msg.send_keys(Keys.ENTER)
            return True
        except TimeoutException:
            raise TimeoutError("Your request has been timed out! Try overriding timeout!")
        except NoSuchElementException:
            return False
        except Exception:
            return False

    # This method will count the no of participants for the group name provided 
Example #22
Source File: base_test.py    From xblock-utils with GNU Affero General Public License v3.0 5 votes vote down vote up
def wait_until_exists(self, selector):
        """ Wait until the specified selector exists on the page """
        wait = WebDriverWait(self.browser, self.timeout)
        wait.until(
            lambda driver: driver.find_element_by_css_selector(selector),
            u"Selector '{}' should exist.".format(selector)
        ) 
Example #23
Source File: base_test.py    From xblock-utils with GNU Affero General Public License v3.0 5 votes vote down vote up
def wait_until_text_in(self, text, elem):
        """ Wait until the specified text appears in the DOM element elem """
        wait = WebDriverWait(elem, self.timeout)
        wait.until(lambda e: text in e.text, u"{} should be in {}".format(text, elem.text)) 
Example #24
Source File: studio_editable_test.py    From xblock-utils with GNU Affero General Public License v3.0 5 votes vote down vote up
def wait_for_runtime_notification(self):
        """ Wait until runtime.notify() has been called """
        wait = WebDriverWait(self.browser, self.timeout)
        wait.until(lambda driver: driver.execute_script('return window.notifications.length > 0;')) 
Example #25
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 5 votes vote down vote up
def participants_count_for_group(self, group_name):
        search = self.browser.find_element_by_css_selector("._3FRCZ")
        search.send_keys(group_name+Keys.ENTER)  # we will send the name to the input key box
        # some say this two try catch below can be grouped into one
        # but I have some version specific issues with chrome [Other element would receive a click]
        # in older versions. So I have handled it spereately since it clicks and throws the exception
        # it is handled safely
        try:
            click_menu = WebDriverWait(self.browser,self.timeout).until(EC.presence_of_element_located(
                (By.CSS_SELECTOR, "._19vo_ > span:nth-child(1)")))
            click_menu.click()
        except TimeoutException:
            raise TimeoutError("Your request has been timed out! Try overriding timeout!")
        except NoSuchElementException as e:
            return "None"
        except Exception as e:
            return "None"
        current_time = dt.datetime.now()
        participants_selector = "div._2LSbZ:nth-child(5) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > span:nth-child(1)"
        while True:
            try:
                participants_count = self.browser.find_element_by_css_selector(participants_selector).text
                if "participants" in participants_count:
                    return participants_count
            except Exception as e:
                pass
            new_time = dt.datetime.now()
            elapsed_time = (new_time - current_time).seconds
            if elapsed_time > self.timeout:
                return "NONE"

    # This method is used to get all the participants 
Example #26
Source File: whatsapp.py    From Simple-Yet-Hackable-WhatsApp-api with Apache License 2.0 5 votes vote down vote up
def goto_main(self):
        try:
            self.browser.refresh()
            Alert(self.browser).accept()
        except Exception as e:
            print(e)
        WebDriverWait(self.browser, self.timeout).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, '._3FRCZ')))



    # get the status message of a person
    # TimeOut is approximately set to 10 seconds 
Example #27
Source File: streaming_generator.py    From classification-of-encrypted-traffic with MIT License 5 votes vote down vote up
def clear_cache(driver, timeout=60):
    """Clear the cookies and cache for the ChromeDriver instance."""
    # navigate to the settings page
    driver.get('chrome://settings/clearBrowserData')

    # wait for the button to appear
    wait = WebDriverWait(driver, timeout)
    wait.until(get_clear_browsing_button)

    # click the button to clear the cache
    get_clear_browsing_button(driver).click()

    # wait for the button to be gone before returning
    wait.until_not(get_clear_browsing_button) 
Example #28
Source File: test-ui.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def test_index(driver, ui_mode, device_user, device_password, screenshot_dir):
    user = driver.find_element_by_id("name")
    user.send_keys(device_user)
    password = driver.find_element_by_id("password")
    password.send_keys(device_password)
    password.submit()
    time.sleep(5)
    screenshots(driver, screenshot_dir, 'index-progress-' + ui_mode)
    wait_driver = WebDriverWait(driver, 20)
    wait_driver.until(EC.presence_of_element_located((By.CLASS_NAME, 'menubutton')))
    time.sleep(5)
    screenshots(driver, screenshot_dir, 'index-' + ui_mode) 
Example #29
Source File: TraTicketBooker.py    From TRA-Ticket-Booker with GNU General Public License v3.0 5 votes vote down vote up
def connect_to_webpage(self):
        url_target_sg = 'http://railway1.hinet.net/csearch.htm'
        url_target_gb = 'http://railway.hinet.net/ctkind2.htm'
        self.driver.delete_all_cookies()
        
        wait = WebDriverWait(self.driver, timeout=6)
        try:
            # Booking Single Ticket.
            if self.book_type == 1:
                self.driver.get(url_target_sg)
                wait.until(
                    EC.presence_of_element_located(
                        (By.TAG_NAME, 'button')
                    )
                )
            # Booking Go-Back Ticket.
            elif self.book_type == 2:
                self.driver.get(url_target_gb)
                wait.until(
                    EC.presence_of_element_located(
                        (By.TAG_NAME, 'button')
                    )
                )
        except:
            self.label_show_result.setText(
                '【連線逾時或是網路不穩定】\n' + 
                '【請檢查網路環境以及是否為尖峰時段。】'
            ) 
Example #30
Source File: test_views.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def test_all_patients_correct_order(self):

        self.selenium.get('%s%s' % (self.live_server_url, '/'))
        self.submit_login(self.providers['coordinator'].username,
                          self.provider_password)

        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("all-patients")))

        # causes a broken pipe error
        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("all-patients")))

        self.assertEquals(self.selenium.current_url,
                          '%s%s' % (self.live_server_url,
                                    reverse('all-patients')))

        # unsure how to test for multiple elements/a certain number of elements
        # WebDriverWait(self.selenium, 60).until(EC.presence_of_element_located((By.ID, "ptlast")))
        # WebDriverWait(self.selenium, 60).until(EC.presence_of_element_located((By.ID, "ptlatest")))

        # test ordered by last name
        pt_tbody = self.selenium.find_element_by_xpath("//div[@class='container']/table/tbody") # this line does throw an error if the id-ed element does not exist
        first_patient_name = pt_tbody.find_element_by_xpath("//tr[2]/td[1]").text
        second_patient_name = pt_tbody.find_element_by_xpath("//tr[3]/td[1]").text
        self.assertLessEqual(first_patient_name, second_patient_name)
        self.assertEqual(first_patient_name, "Action, No I.")

        # # test order by latest activity
        # # more difficult to test attributes, I'm just testing that the first
        # # name is correct
        # pt_last_tbody = self.selenium.find_element_by_xpath(
        #     "//div[@id='ptlatest']/table/tbody")
        # first_patient_name = pt_last_tbody.find_element_by_xpath(
        #     ".//tr[2]/td[1]/a").get_attribute("text")
        # self.assertEqual(first_patient_name, "Brodeltein, Juggie B.")