Python selenium.webdriver.common.by.By 模块,ID 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用selenium.webdriver.common.by.By.ID

项目:ScrapePremiumInsights    作者:abagh0703    | 项目源码 | 文件源码
def login_linkedin(your_username, your_password):
    driver.get(
        'https://www.linkedin.com/uas/login?session_redirect=%2Fvoyager%2FloginRedirect%2Ehtml&fromSignIn=true&trk=uno-reg-join-sign-in')  # Login page
    wait.until(EC.presence_of_element_located((By.ID, 'btn-primary')))  # Wait for the sign in button to load first
    login = driver.find_element_by_id('session_key-login')  # Get username box
    login.send_keys(your_username)  # Enter username
    password = driver.find_element_by_id('session_password-login')  # Get password box
    password.send_keys(your_password)  # Enter your password
    password.submit()
    print 'logged in: ' + your_username
    time.sleep(7)
    # Capcha
    if 'a quick security' in driver.page_source:
        time.sleep(30)
        waitInput = raw_input("Do the security check then press enter here")
        time.sleep(10)
    # When signing in from a new location
    if 'pin' in driver.page_source:
        pin = driver.find_element_by_id("verification-code")
        pin.send_keys(raw_input("Enter pin for: " + your_username))
        pin.submit()
        time.sleep(10)

##  Establish variables
项目:python3_crawl    作者:princewen    | 项目源码 | 文件源码
def login():
    """??????,??????????"""
    driver.get(start_url)
    wait = WebDriverWait(driver,10)
    try:
        username = wait.until(EC.presence_of_element_located((By.ID,"loginname")))
        password = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input')))
        username.send_keys(user)
        password.send_keys(passwd)
        btn = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="pl_login_form"]/div/div[3]/div[6]/a/span')))
        btn.click()
    except TimeoutException:
        print ("??")
        return
    except NoSuchElementException:
        print ("?????? ")
        return
项目:TRA-Ticket-Booker    作者:gw19    | 项目源码 | 文件源码
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' + 
                '???????????????????'
            )
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def log_in_via_admin(self, user, password):
        """Make user into staff, login via admin, then undo staff status"""
        is_already_staff = user.is_staff
        if not is_already_staff:
            user.is_staff = True
            user.save()

        # Getting admin/ twice to work around an CSRF issue
        self.browser.get("admin/")
        self.browser.get("admin/")
        self.browser.wait_until_loaded(By.ID, "id_username")
        self.browser.driver.find_element_by_id("id_username").send_keys(user.username)
        self.browser.driver.find_element_by_id("id_password").send_keys(password)
        self.browser.driver.find_element_by_css_selector("input[type=submit]").click()
        # This is the 'Welcome, username' box on the upper right
        self.browser.wait_until_loaded(By.ID, "user-tools")

        if not is_already_staff:
            user.is_staff = False
            user.save()
        return user
项目:pytest-needle    作者:jlane9    | 项目源码 | 文件源码
def test_example_page_with_mask(needle):
    """Example for comparing page with a mask

    :param NeedleDriver needle: NeedleDriver instance
    :return:
    """

    # Navigate to web page
    needle.driver.get('https://www.google.com')

    # Ensure the cursor does not appear in the screenshot
    footer = needle.driver.find_elements_by_xpath('//div[@class="fbar"]')

    if footer:
        footer[0].click()

    # Take a entire page screen diff, ignore the doodle banner
    needle.assert_screenshot('search_page', exclude=[(By.ID, 'hplogo'), (By.ID, 'prm')], threshold=80)
项目:pytest-needle    作者:jlane9    | 项目源码 | 文件源码
def test_example_element(needle):
    """Example for comparing individual elements

    :param NeedleDriver needle: NeedleDriver instance
    :return:
    """

    # Navigate to web page
    needle.driver.get('https://www.google.com')

    # Ensure the cursor does not appear in the screenshot
    footer = needle.driver.find_elements_by_xpath('//div[@class="fbar"]')

    if footer:
        footer[0].click()

    # Take an element screen diff
    needle.assert_screenshot('search_field', (By.ID, 'tsf'), threshold=80)
项目:Dallinger    作者:Dallinger    | 项目源码 | 文件源码
def participate(self):
        """Finish reading and send text"""
        try:
            logger.info("Entering participate method")
            ready = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, 'finish-reading')))
            stimulus = self.driver.find_element_by_id('stimulus')
            story = stimulus.find_element_by_id('story')
            story_text = story.text
            logger.info("Stimulus text:")
            logger.info(story_text)
            ready.click()
            submit = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, 'submit-response')))
            textarea = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, 'reproduction')))
            textarea.clear()
            text = self.transform_text(story_text)
            logger.info("Transformed text:")
            logger.info(text)
            textarea.send_keys(text)
            submit.click()
            return True
        except TimeoutException:
            return False
项目:Dallinger    作者:Dallinger    | 项目源码 | 文件源码
def participate(self):
        random.seed(self.worker_id)
        chatbot = random.choice(self.PERSONALITIES)
        WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.ID, 'send-message')))
        logger.info("Entering participate method")
        start = time.time()
        while (time.time() - start) < self.TOTAL_CHAT_TIME:

            self.wait_to_send_message()
            history = self.get_chat_history()
            logger.info("History: %s" % history)
            if history and history[-1]:
                logger.info("Responding to: %s" % history[-1])
                output = chatbot.respond(history[-1])
            else:
                logger.info("Using random greeting.")
                output = random.choice(self.GREETINGS)
            logger.info("Output: %s" % output)
            self.send_message(output)

        self.leave_chat()
项目:webtesting    作者:madlenkk    | 项目源码 | 文件源码
def step_03_check_basket_is_empty(selenium):
    # //*[@id="messages"]/div[2]/p
    # pytest.set_trace()
    # el = selenium.find_element_by_id('messages')
    # import time
    # time.sleep(1)
    # assert 'Your basket is now empty' in el.text

    WebDriverWait(selenium, 2).until(
        EC.text_to_be_present_in_element(
            # (By.ID, 'messages'),
            (By.XPATH, '//p[contains(text(),"Your basket is now empty")]'),
            'Your basket is now empty'
         )
    )

    # empty_alert = selenium.find_element(By.XPATH,'//p[contains(text(),"Your basket is now empty")]')
项目:TestRewrite    作者:osqa-interns    | 项目源码 | 文件源码
def delete_assignment(target_element, is_published):
    """
    target_element: the web element of assignment to be deleted
    """
    target_element.click()
    sleep(1)
    if is_published:
        teacher.find(
            By.ID, "edit-assignment-button"
        ).click()
        sleep(1)
    delete_button = teacher.wait.until(
        expect.element_to_be_clickable(
            (By.XPATH, '//button[contains(@class,"delete-link")]')
        )
    )
    teacher.scroll_to(delete_button)
    sleep(1)
    delete_button.click()
    teacher.find(
        By.XPATH, '//button[contains(text(), "Yes")]'
    ).click()
    sleep(1)
项目:TestRewrite    作者:osqa-interns    | 项目源码 | 文件源码
def goto_course_list(self):
        """Go to the course picker."""
        long_wait = WebDriverWait(self.driver, 30)
        try:
            long_wait.until(
                expect.presence_of_element_located(
                    (By.ID, 'ox-react-root-container')
                )
            )
            if 'tutor' in self.current_url():
                self.find(By.CSS_SELECTOR, '.ui-brand-logo').click()
                self.page.wait_for_page_load()
            else:
                raise HTTPError('Not currently on an OpenStax Tutor webpage:' +
                                '%s' % self.current_url())
        except Exception as ex:
            raise ex
项目:ShuoshuoMonitor    作者:aploium    | 项目源码 | 文件源码
def find_element(self, by=By.ID, value=None):
        if not By.is_valid(by) or not isinstance(value, str):
            raise InvalidSelectorException("Invalid locator values passed in")

        if self._w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self._execute(Command.FIND_CHILD_ELEMENT,
                             {"using": by, "value": value})['value']
项目:ShuoshuoMonitor    作者:aploium    | 项目源码 | 文件源码
def find_elements(self, by=By.ID, value=None):
        if not By.is_valid(by) or not isinstance(value, str):
            raise InvalidSelectorException("Invalid locator values passed in")

        if self._w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self._execute(Command.FIND_CHILD_ELEMENTS,
                             {"using": by, "value": value})['value']
项目:ShuoshuoMonitor    作者:aploium    | 项目源码 | 文件源码
def find_element(self, by=By.ID, value=None):
        """
        'Private' method used by the find_element_by_* methods.

        :Usage:
            Use the corresponding find_element_by_* instead of this.

        :rtype: WebElement
        """
        if not By.is_valid(by) or not isinstance(value, str):
            raise InvalidSelectorException("Invalid locator values passed in")
        if self.w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value
        return self.execute(Command.FIND_ELEMENT,
                             {'using': by, 'value': value})['value']
项目:proximus_auto_add_vol_pack    作者:salcin    | 项目源码 | 文件源码
def go_to_internet(self):

        # if a ad is displayed, dismiss it
        try:
            WebDriverWait(self.browser, 5).until(EC.presence_of_element_located((By.ID, "ns_7_7OGJPDU51OIB50IVTR847P20G2_")))       # wait 5 sec to find if a ad is displayed
            self.browser.find_element_by_xpath('//a[@href="javascript: void(0)"]').click()
        except Exception:
            pass

        # wait the loading page
        self.wait_before_continue('ns_7_7OGJPDU518D6A0ACILTFQT2004_myBillAndProducts')

        try:
            self.browser.find_element_by_xpath('//i[contains(@class, "icon-Internetlaptop")]').click()
            self.wait_before_continue("ns_7_7OGJPDU51OKG60I9TQGKIB1004_myFixedInternetServices")

        except:
            self.error_take_screenshot('to go on the internet page')
            exit(3)
项目:directory-tests    作者:uktrade    | 项目源码 | 文件源码
def get_file_log_handler(
        log_formatter, *, log_level=logging.DEBUG, task_id: str = None) \
        -> logging.FileHandler:
    """Configure the console logger.

    Will use DEBUG logging level by default.

    :param log_formatter: specifies how the log entries will look like
    :param log_level: specifies logging level, e.g.: logging.ERROR
    :param task_id: (optional) ID of the parallel task
    :return: configured console log handler
    """
    if task_id:
        log_file = os.path.join("reports", ("behave-%s.log" % task_id))
    else:
        log_file = os.path.join("reports", "behave.log")
    print("Behave log file: {}".format(log_file))
    file_handler = logging.FileHandler(log_file)
    file_handler.setLevel(log_level)
    file_handler.setFormatter(log_formatter)
    return file_handler
项目:directory-tests    作者:uktrade    | 项目源码 | 文件源码
def wait_for_visibility(
        driver: webdriver, *, by_css: str = None,
        by_id: str = None, time_to_wait: int = 5):
    """Wait until element is visible.

    :param driver: Selenium driver
    :param by_css: CSS selector to locate the element to wait for
    :param by_id: ID of the element to wait for
    :param time_to_wait: maximum number of seconds to wait
    """
    assert by_id or by_css, "Provide ID or CSS selector"
    if by_css:
        by_locator = (By.CSS_SELECTOR, by_css)
    else:
        by_locator = (By.ID, by_id)
    WebDriverWait(driver, time_to_wait).until(
        expected_conditions.visibility_of_element_located(by_locator))
项目:directory-tests    作者:uktrade    | 项目源码 | 文件源码
def check_if_element_is_not_present(
        driver: webdriver, *, by_css: str = None,
        by_id: str = None, element_name: str = ""):
    """Find element by CSS selector or it's ID.

    :param driver: Selenium driver
    :param by_css: CSS selector to locate the element to wait for
    :param by_id: ID of the element to wait for
    :return: found WebElement
    """
    assert by_id or by_css, "Provide ID or CSS selector"
    try:
        if by_css:
            driver.find_element_by_css_selector(by_css)
        else:
            driver.find_element_by_id(by_id)
        found = True
    except NoSuchElementException:
        found = False
    with assertion_msg(
            "Expected not to find %s element identified by '%s'", element_name,
            by_id or by_css):
        assert not found
项目:directory-tests    作者:uktrade    | 项目源码 | 文件源码
def find_element(
        driver: webdriver, *, by_css: str = None,
        by_id: str = None, element_name: str = "") -> WebElement:
    """Find element by CSS selector or it's ID.

    :param driver: Selenium driver
    :param by_css: CSS selector to locate the element to wait for
    :param by_id: ID of the element to wait for
    :param element_name: (optional) human friend element name
    :return: found WebElement
    """
    assert by_id or by_css, "Provide ID or CSS selector"
    with selenium_action(
            driver, "Couldn't find element %s using '%s'", element_name,
            by_css or by_id):
        if by_css:
            element = driver.find_element_by_css_selector(by_css)
        else:
            element = driver.find_element_by_id(by_id)
    return element
项目:directory-tests    作者:uktrade    | 项目源码 | 文件源码
def find_elements(
        driver: webdriver, *, by_css: str = None,
        by_id: str = None) -> list:
    """Find element by CSS selector or it's ID.

    :param driver: Selenium driver
    :param by_css: CSS selector to locate the element to wait for
    :param by_id: ID of the element to wait for
    :return: a list of found WebElements
    """
    assert by_id or by_css, "Provide ID or CSS selector"
    with selenium_action(
            driver, "Couldn't find elements using '%s'", by_css or by_id):
        if by_css:
            elements = driver.find_elements_by_css_selector(by_css)
        else:
            elements = driver.find_elements_by_id(by_id)
    return elements
项目:bankscraper    作者:kamushadenes    | 项目源码 | 文件源码
def login(self):
        if not self.quiet:
            print('[*] Logging in as {}'.format(self.account.document))

        try:
            self.session.get(self.login_url)

            elem = self.wait.until(EC.visibility_of_element_located((By.ID, 'cpf')))
            elem.send_keys(self.account.document)
            elem.send_keys(Keys.ENTER)

            elem = self.wait.until(EC.visibility_of_element_located((By.ID, 'password')))
            elem.send_keys(self.account.password)

            for b in self.session.find_elements_by_class_name('botao'):
                if b.get_attribute('data-bind'):
                    if 'userAuthentication' in b.get_attribute('data-bind'):
                        b.click()
                        break
        except Exception:
            traceback.print_exc()
            exit(1)
项目:selenium_extensions    作者:pythad    | 项目源码 | 文件源码
def click_on_element(driver, element_locator):
    '''Clicks on a Selenium element represented by ``element_locator``

    Args:
        element_locator ((selenium.webdriver.common.by.By., str)): element locator described using `By`. Take a look at `Locate elements By <http://selenium-python.readthedocs.io/api.html#locate-elements-by>`_ for more info.

    Example:
        ::

            from selenium import webdriver
            from selenium.webdriver.common.by import By
            from selenium_extensions.core import click_on_element


            driver = webdriver.Chrome()
            ...
            click_on_element(driver, (By.ID, 'form-submit-button'))
    '''
    element = driver.find_element(*element_locator)
    element.click()
项目:biweeklybudget    作者:jantman    | 项目源码 | 文件源码
def test_08_invalid_trans_id(self, base_url, selenium):
        self.get(selenium, base_url + '/reconcile')
        assert self.get_reconciled(selenium) == {}
        script = 'reconciled[1234] = [4, "OFXNONE"];'
        selenium.execute_script(script)
        assert self.get_reconciled(selenium) == {
            1234: [4, "OFXNONE"]
        }
        # click submit button
        selenium.find_element_by_id('reconcile-submit').click()
        sleep(1)
        self.wait_for_jquery_done(selenium)
        assert self.get_reconciled(selenium) == {
            1234: [4, "OFXNONE"]
        }
        msg = selenium.find_element_by_id('reconcile-msg')
        assert msg.text == 'Error 400: Invalid Transaction ID: 1234'
        assert 'alert-danger' in msg.get_attribute('class')
项目:biweeklybudget    作者:jantman    | 项目源码 | 文件源码
def wait_until_clickable(self, driver, elem_id, by=By.ID, timeout=10):
        """
        Wait for the modal to be shown.

        :param driver: Selenium driver instance
        :type driver: selenium.webdriver.remote.webdriver.WebDriver
        :param elem_id: element ID
        :type elem_id: str
        :param by: What method to use to find the element. This must be one of
          the strings which are values of
          :py:class:`selenium.webdriver.common.by.By` attributes.
        :type by: str
        :param timeout: timeout in seconds
        :type timeout: int
        """
        WebDriverWait(driver, timeout).until(
            EC.element_to_be_clickable((by, elem_id))
        )
项目:amazon_order_history_scraper    作者:drewctate    | 项目源码 | 文件源码
def find_element(self, by=By.ID, value=None):
        if self._w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self._execute(Command.FIND_CHILD_ELEMENT,
                             {"using": by, "value": value})['value']
项目:amazon_order_history_scraper    作者:drewctate    | 项目源码 | 文件源码
def find_elements(self, by=By.ID, value=None):
        if self._w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self._execute(Command.FIND_CHILD_ELEMENTS,
                             {"using": by, "value": value})['value']
项目:amazon_order_history_scraper    作者:drewctate    | 项目源码 | 文件源码
def find_element(self, by=By.ID, value=None):
        """
        'Private' method used by the find_element_by_* methods.

        :Usage:
            Use the corresponding find_element_by_* instead of this.

        :rtype: WebElement
        """
        if self.w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value
        return self.execute(Command.FIND_ELEMENT, {
            'using': by,
            'value': value})['value']
项目:NetEaseMusicCrawler    作者:yaochao    | 项目源码 | 文件源码
def _wait_and_switch(self, driver):
        try:
            # wait
            element = WebDriverWait(driver=driver, timeout=10).until(
                expected_conditions.presence_of_element_located((By.ID, 'date_views')))
            # switch
            driver.switch_to.window(driver.current_window_handle)
        except:
            logger.error('timeout but ajax until not completed')
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def find_id_with_timeout(driver, ID, timeout=TIMEOUT):
    return WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((By.ID, ID))
    )
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def find_visible_id_with_timeout(driver, ID, timeout=TIMEOUT):
    return WebDriverWait(driver, timeout).until(
            EC.visibility_of_element_located((By.ID, ID))
    )
项目:pyselenium-js    作者:neetjn    | 项目源码 | 文件源码
def test_ng_debugging(self):
        """Test: Enable angular debugging and verify binded elements"""
        self.page.js.ng_enable_debugging()
        WebDriverWait(self.page.browser, 5).until(EC.presence_of_element_located((By.ID, 'app')))
        self.page.js.trigger_event(
            element=self.page.user_name_field,
            event='focus'
        )  # wait for page reload
        self.assertGreater(
            len(self.page.binded_elements), 0,
            'Expected at least one binded element found none'
        )
项目:sbu-bot    作者:danielamorais    | 项目源码 | 文件源码
def login(email, senha, firefox):
    firefox.get('http://acervus.unicamp.br/asp/login.asp?modo_busca=rapida&content=mensagens&iBanner=0&iEscondeMenu=0&iSomenteLegislacao=0&iIdioma=0')
    firefox.implicitly_wait(10)
    WebDriverWait(firefox, 60).until(EC.visibility_of_element_located((By.ID, 'button1')))
    try:
        input_login = firefox.find_element_by_name("codigo")
        input_login.send_keys(email)
        input_pwd = firefox.find_element_by_name("senha")
        input_pwd.send_keys(senha)
        send_button = firefox.find_element_by_id("button1")
        send_button.click()
        WebDriverWait(firefox, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, 'justificado')))
    except Exception, err:
        error_message = "Erro no login. Verifique usuário e senha."
        print error_message
        logging.exception(error_message)
        raise
    return
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def create_ticket_type(cls, name=None, description=None, cost=None, release=True, quantity=100):
        # Fill dummy data if not provided
        if name == None: name = str(randint(0, 100000))
        if description == None: description = "This is the demo description for %s" % name
        if cost == None: cost = str(randint(0, 200))
        else: cost = "%.2f" % (cost / 100.0)
        # Enact an administration login
        cls.admin_login()
        # Go to the ticket type add page
        cls.browser.get(cls.route_path("admin_ticket_type_add"))
        cls.browser.find_element(By.ID, "name").send_keys(name)
        cls.browser.find_element(By.ID, "description").send_keys(description)
        cls.browser.find_element(By.ID, "cost").send_keys(cost)
        # Check the group boxes so that purchaase is allowed
        cls.browser.find_element(By.ID, "raven-group").click()
        cls.browser.find_element(By.ID, "admin-group").click()
        cls.browser.find_element(By.ID, "alumni-group").click()
        cls.browser.find_element(By.ID, "committee-group").click()
        cls.browser.find_element(By.ID, "submit").click()
        # Ensure it added
        cls.browser.get(cls.route_path("admin_tickets"))
        assert name in cls.browser.page_source
        # If we have been told to release then do so
        if release: cls.release_tickets(name, quantity=quantity)
        # Logout of admin account
        cls.logout()
        # Return its details
        return (name, description, cost, quantity)
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def release_tickets(cls, type_name, quantity=100):
        # Login
        cls.admin_login()
        # Find the release link and click it
        cls.browser.get(cls.route_path("admin_tickets"))
        row = 1
        found = False
        while cls.is_element_present("//table/tbody/tr[%i]/td[1]" % row):
            name = cls.browser.find_element_by_xpath("//table/tbody/tr[%i]/td[1]" % row).text
            if type_name in name:
                cell = cls.browser.find_element_by_xpath("//table/tbody/tr[%i]/td[4]" % row)
                cell.find_element(By.CLASS_NAME, "release_tick_link").click()
                found = True
                break
            row += 1
        assert found, "Didn't find release link for ticket type!"
        # Now actually release some tickets
        cls.browser.find_element(By.ID, "number").send_keys(str(quantity))
        cls.browser.find_element(By.ID, "submit").click()
        # Deal with modal alert
        try:
            cls.browser.switch_to_alert().accept()
        except Exception:
            pass # Catch for PhantomJS
        # Logout
        cls.logout()
        # Return quantity
        return quantity
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def raven_login(cls, crsid=None, password=None, fill_details=True):
        if crsid == None:
            crsid = "test0%03d" % ( randint(0, 400) )
            password = "test"
        # First ensure we are logged out
        cls.logout()
        # Now login
        cls.browser.get("http://localhost:%i/" % cls.port_num)
        # Click the raven link
        link = cls.browser.find_element(By.ID, "ravenbutton")
        link.click()
        sleep(1)
        # We should now be at the Raven testing login page
        assert "Demonstration Authentication Service" in cls.browser.page_source
        assert Raven.our_description in cls.browser.page_source
        # Fill in the login details
        user = cls.browser.find_element(By.ID, "userid")
        user.send_keys(crsid)
        pwd = cls.browser.find_element(By.ID, "pwd")
        pwd.send_keys(password)
        cls.browser.find_element(By.NAME, "credentials").submit()
        # Fill details automatically fills the profile
        if fill_details:
            filled_state = {
                "fullname": "Automated Test User",
                "dob_day": "15",
                "dob_month": "3",
                "dob_year": "1987",
                "photofile": cls.root_path() + "/data/profile_images/dummy.png",
                "college": "sidney-sussex",
                "grad_status": "undergrad",
            }
            # Now run a full valid fill and check for no validation fault
            cls.browser.get(cls.route_path("user_profile_edit"))
            for key in filled_state:
                cls.browser.find_element(By.ID, key).send_keys(filled_state[key])
            # Submit
            cls.browser.find_element(By.ID, "submit").click()
        # Return credentials used
        return (crsid, password)
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def admin_login(cls, username=None, password=None):
        # Fill the default values
        if username == None:
            username = "admin"
            password = "password"
        # Logout, then login
        cls.logout()
        cls.browser.get(cls.route_path("admin_login"))
        cls.browser.get(cls.route_path("admin_login"))
        time.sleep(1) # Just ensure we are here
        cls.browser.find_element(By.ID, "username").send_keys(username)
        cls.browser.find_element(By.ID, "password").send_keys(password)
        cls.browser.find_element(By.ID, "submit").click()
        # Return login credentials used
        return (username, password)
项目:picoCTF    作者:royragsdale    | 项目源码 | 文件源码
def find_id_with_timeout(driver, ID, timeout=TIMEOUT):
    return WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((By.ID, ID))
    )
项目:picoCTF    作者:royragsdale    | 项目源码 | 文件源码
def find_visible_id_with_timeout(driver, ID, timeout=TIMEOUT):
    return WebDriverWait(driver, timeout).until(
            EC.visibility_of_element_located((By.ID, ID))
    )
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def _change_focus(self, by, selector, focus = True, message = None):
        description = self.describeElement(by, selector)
        wait_for = self.getDefaultWaitFor()
        change = 'focus' if focus else 'blur'
        element = self.assertElementPresent(by, selector, message, wait_for = wait_for)
        self.log("{0} on {1}{2}".format(change, description, \
            ", because " + message if message else ""))
        script = ""
        if by == By.ID:
            script = "jQuery(\"#{0}\")".format(selector)
        elif by == By.CSS_SELECTOR:
            script = "jQuery(\"{0}\")".format(selector)
        else:
            self.onFail(by, selector, message, "Cannot {0} for this selector type (yet).".\
                format(change))
        script = "{0}.{1}();".format(script, change)
        self.log("{0} on {1} using {2}".format(change, description, script))
        self.driver.execute_script(script)
        return element
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def populateFormByID(self, formData):
        for form_id, value in formData.iteritems():
            self.sendKeys(By.ID, form_id, value, message = "Setting form field")
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_element_by_id(self, id_):
        """Finds element within this element's children by ID.

        :Args:
            - id_ - ID of child element to locate.
        """
        return self.find_element(by=By.ID, value=id_)
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_elements_by_id(self, id_):
        """Finds a list of elements within this element's children by ID.

        :Args:
            - id_ - Id of child element to find.
        """
        return self.find_elements(by=By.ID, value=id_)
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def id(self):
        """Internal ID used by selenium.

        This is mainly for internal use. Simple use cases such as checking if 2
        webelements refer to the same element, can be done using ``==``::

            if element1 == element2:
                print("These 2 are equal")

        """
        return self._id
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_elements(self, by=By.ID, value=None):
        if not By.is_valid(by) or not isinstance(value, str):
            raise InvalidSelectorException("Invalid locator values passed in")

        if self._w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self._execute(Command.FIND_CHILD_ELEMENTS,
                             {"using": by, "value": value})['value']
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_element_by_id(self, id_):
        """Finds an element by id.

        :Args:
         - id\_ - The id of the element to be found.

        :Usage:
            driver.find_element_by_id('foo')
        """
        return self.find_element(by=By.ID, value=id_)
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_elements_by_id(self, id_):
        """
        Finds multiple elements by id.

        :Args:
         - id\_ - The id of the elements to be found.

        :Usage:
            driver.find_elements_by_id('foo')
        """
        return self.find_elements(by=By.ID, value=id_)
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_element(self, by=By.ID, value=None):
        """
        'Private' method used by the find_element_by_* methods.

        :Usage:
            Use the corresponding find_element_by_* instead of this.

        :rtype: WebElement
        """
        if not By.is_valid(by) or not isinstance(value, str):
            raise InvalidSelectorException("Invalid locator values passed in")
        if self.w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value
        return self.execute(Command.FIND_ELEMENT,
                             {'using': by, 'value': value})['value']
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_elements(self, by=By.ID, value=None):
        """
        'Private' method used by the find_elements_by_* methods.

        :Usage:
            Use the corresponding find_elements_by_* instead of this.

        :rtype: list of WebElement
        """
        if not By.is_valid(by) or not isinstance(value, str):
            raise InvalidSelectorException("Invalid locator values passed in")
        if self.w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self.execute(Command.FIND_ELEMENTS,
                             {'using': by, 'value': value})['value']
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def find_elements(self, by=By.ID, value=None):
        return self._dispatch("find", (by, value, self._driver), "find_elements", (by, value))