python类ID的实例源码

scrapeCompany.py 文件源码 项目:ScrapePremiumInsights 作者: abagh0703 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
??selenium???????????.py 文件源码 项目:python3_crawl 作者: princewen 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
TraTicketBooker.py 文件源码 项目:TRA-Ticket-Booker 作者: gw19 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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' + 
                '???????????????????'
            )
page.py 文件源码 项目:micromasters 作者: mitodl 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
test_example.py 文件源码 项目:pytest-needle 作者: jlane9 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
test_example.py 文件源码 项目:pytest-needle 作者: jlane9 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
experiment.py 文件源码 项目:Dallinger 作者: Dallinger 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
experiment.py 文件源码 项目:Dallinger 作者: Dallinger 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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()
test_case_02_remove_from_basket_empty.py 文件源码 项目:webtesting 作者: madlenkk 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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")]')
clean_up_calendar.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
helper.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
webelement.py 文件源码 项目:ShuoshuoMonitor 作者: aploium 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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']
webelement.py 文件源码 项目:ShuoshuoMonitor 作者: aploium 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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']
webdriver.py 文件源码 项目:ShuoshuoMonitor 作者: aploium 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:proximus_auto_add_vol_pack 作者: salcin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:directory-tests 作者: uktrade 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:directory-tests 作者: uktrade 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:directory-tests 作者: uktrade 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:directory-tests 作者: uktrade 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:directory-tests 作者: uktrade 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
alelo.py 文件源码 项目:bankscraper 作者: kamushadenes 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
core.py 文件源码 项目:selenium_extensions 作者: pythad 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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()
test_reconcile.py 文件源码 项目:biweeklybudget 作者: jantman 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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')
acceptance_helpers.py 文件源码 项目:biweeklybudget 作者: jantman 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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))
        )
webelement.py 文件源码 项目:amazon_order_history_scraper 作者: drewctate 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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']
webelement.py 文件源码 项目:amazon_order_history_scraper 作者: drewctate 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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']
webdriver.py 文件源码 项目:amazon_order_history_scraper 作者: drewctate 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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']
downloadhandlers.py 文件源码 项目:NetEaseMusicCrawler 作者: yaochao 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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')
common.py 文件源码 项目:picoCTF 作者: picoCTF 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def find_id_with_timeout(driver, ID, timeout=TIMEOUT):
    return WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((By.ID, ID))
    )
common.py 文件源码 项目:picoCTF 作者: picoCTF 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def find_visible_id_with_timeout(driver, ID, timeout=TIMEOUT):
    return WebDriverWait(driver, timeout).until(
            EC.visibility_of_element_located((By.ID, ID))
    )


问题


面经


文章

微信
公众号

扫码关注公众号