python类CSS_SELECTOR的实例源码

WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def wait_for_presence(self, selector='', **kwargs):
        '''
        Wait for an element to be present. (Does not need to be visible.)

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.presence_of_element_located((by, selector)) or
                       EC.presence_of_elements_located((by, selector)),
                       **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def wait_for_clickable(self, selector='', **kwargs):
        '''
        Wait for an element to be clickable.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.element_to_be_clickable((by, selector)), **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def wait_for_visible(self, selector='', **kwargs):
        '''
        Wait for an element to be visible.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.visibility_of_element_located((by, selector)),
                       **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def wait_for_invisible(self, selector='', **kwargs):
        '''
        Wait for an element to be invisible.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.invisibility_of_element_located((by, selector)),
                       **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def wait_for_text(self, selector='', text='', **kwargs):
        '''
        Wait for an element to contain a specific string.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        text: str
            The string to look for. This must be precise.
            (Case, punctuation, UTF characters... etc.)
        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.text_to_be_present_in_element((by, selector),
                                                        text), **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def wait_for_selected(self, selector='', selected=True, **kwargs):
        '''
        Wait for an element (checkbox/radio) to be selected.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        selected: bool
            Whether or not the element should be selected. Default True

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.element_located_selection_state_to_be((by, selector),
                                                                selected), **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def wait_for_value(self, selector='', value='', **kwargs):
        '''
        Wait for an element to contain a specific string.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        value: str
            The string to look for. This must be precise.
            (Case, punctuation, UTF characters... etc.)
        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.text_to_be_present_in_element_value((by, selector),
                                                              value), **kwargs)
selenium.py 文件源码 项目:SerpScrap 作者: ecoron 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _find_next_page_element(self):
        """Finds the element that locates the next page for any search engine.

        Returns:
            The element that needs to be clicked to get to the next page or a boolean value to
            indicate an error condition.
        """
        if self.search_type == 'normal':
            selector = self.next_page_selectors[self.search_engine_name]
            try:
                # wait until the next page link is clickable
                WebDriverWait(self.webdriver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, selector)))
            except (WebDriverException, TimeoutException):
                self._save_debug_screenshot()
                # raise Exception('{}: Cannot locate next page element: {}'.format(self.name, str(e)))
            try:
                return self.webdriver.find_element_by_css_selector(selector)
            except Exception:
                logger.error('failed find_element_by_css_selector, sleep 30 sec')
                time.sleep(30)
                pass

        elif self.search_type == 'image':
            self.page_down()
            if self.search_engine_name == 'google':
                return self.webdriver.find_element_by_css_selector('input._kvc')
            else:
                return True
test_ui.py 文件源码 项目:integration 作者: mendersoftware 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def test_basic_inventory(self):
        ui_test_banner()
        driver = self.init_driver()
        self.login(driver)
        assert self.click_button(driver, "Devices")
        authorized_device = self.wait_for_element(driver, By.CSS_SELECTOR, "div.rightFluid.padding-right tbody.clickable > tr")
        assert authorized_device
        authorized_device.click()
        assert "vexpress-qemu" in authorized_device.text
        assert "mender-image-master" in authorized_device.text

        # make sure basic inventory items are there
        assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'Linux version')]")
        assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'eth0')]")
        assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'ARM')]")
        ui_test_success()
        self.destroy_driver(driver)
test_ui.py 文件源码 项目:integration 作者: mendersoftware 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_deployment_in_progress(self):
        ui_test_banner()
        driver = self.init_driver()
        self.login(driver)
        assert self.click_button(driver, "Deployments")

        timeout = time.time() + 60*5
        while time.time() < timeout:
                e = self.wait_for_element(driver, By.CSS_SELECTOR, "span.status.inprogress")
                if e.text == '1':
                    break
                time.sleep(1)
        else:
            raise Exception("Deployment never in progress")

        ui_test_success()
        self.destroy_driver(driver)
test_ui.py 文件源码 项目:integration 作者: mendersoftware 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_deployment_successful(self):
        ui_test_banner()
        driver = self.init_driver()
        self.login(driver)
        assert self.click_button(driver, "Deployments")

        timeout = time.time() + 60*5
        while time.time() < timeout:
                e = self.wait_for_element(driver, By.CSS_SELECTOR, "span.status.success")
                if e.text == '1':
                    break
                time.sleep(1)
        else:
            raise Exception("Deployment never completed")

        ui_test_success()
        self.destroy_driver(driver)
volumespage.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def view_volume(self, name):
        row = self._get_row_with_volume_name(name)
        name_link = row.cells['name'].find_element(by.By.CSS_SELECTOR, 'a')
        name_link.click()
select.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def deselect_by_value(self, value):
        """Deselect all options that have a value matching the argument. That is, when given "foo" this
           would deselect an option like:

            <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

            throws NoSuchElementException If there is no option with specisied value in SELECT
        """
        if not self.is_multiple:
            raise NotImplementedError("You may only deselect options of a multi-select")
        matched = False
        css = "option[value = %s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        for opt in opts:
            self._unsetSelected(opt)
            matched = True
        if not matched:
            raise NoSuchElementException("Could not locate element with value: %s" % value)
basic_test.py 文件源码 项目:micromasters 作者: mitodl 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def test_profile_navigation(self, browser, base_test_data):
        """
        Nothing should break when navigating to the profile and back to learners search page
        """
        create_enrolled_user_batch(2, program=base_test_data.program, is_staff=False)

        browser.get("/learners")
        browser.click_when_loaded(By.CLASS_NAME, 'menu-icon')
        browser.wait().until(
            lambda driver: "open" in driver.find_element_by_class_name('nav-drawer').get_attribute('class')
        )
        browser.click_when_loaded(By.CSS_SELECTOR, 'a .profile-image')
        browser.wait_until_loaded(By.CLASS_NAME, 'user-page')
        # Go back to learners
        browser.click_when_loaded(By.CLASS_NAME, 'menu-icon')
        browser.wait().until(
            lambda driver: "open" in driver.find_element_by_class_name('nav-drawer').get_attribute('class')
        )
        browser.click_when_loaded(By.CSS_SELECTOR, "a[href='/learners']")
        browser.wait_until_loaded(By.CLASS_NAME, 'learner-results')
select.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
            raise NoSuchElementException("Cannot locate option with value: %s" % value)
helper.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 26 收藏 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
helper.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def execises_logout(self):
        """Exercises logout helper."""
        wait = WebDriverWait(self.driver, 3)
        try:
            wait.until(
                expect.element_to_be_clickable(
                    (By.ID, 'navbar-dropdown')
                )
            ).click()
            wait.until(
                expect.element_to_be_clickable(
                    (By.CSS_SELECTOR, '[type="submit"]')
                )
            ).click()
            self.page.wait_for_page_load()
        except NoSuchElementException:
            # Different page, but uses the same logic and link text
            self.find(By.CSS_SELECTOR, '[data-method]').click()
helper.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def goto_calendar(self):
        """Return the teacher to the calendar dashboard."""
        print('Enter: goto_calendar')
        try:
            print('Try to return to the calendar')
            self.find(By.CSS_SELECTOR, '.course-name').click()
            print('Succeeded')
            self.page.wait_for_page_load()
        except:
            print('Failed, Try to return to the calendar using the Brand')
            try:
                self.find(
                    By.CSS_SELECTOR,
                    '.brand'
                ).click()
                print('Succeeded')
                self.page.wait_for_page_load()
            except:
                print('Failed, Load manually')
                self.get(
                    'https://' +
                    '/'.join(self.driver.current_url.split('/')[2:5])
                )
                pass
        print('Exit: goto_calendar')
select.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

           throws NoSuchElementException If there is no option with specisied value in SELECT
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
            raise NoSuchElementException("Cannot locate option with value: %s" % value)
select.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def deselect_by_value(self, value):
        """Deselect all options that have a value matching the argument. That is, when given "foo" this
           would deselect an option like:

            <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

            throws NoSuchElementException If there is no option with specisied value in SELECT
        """
        if not self.is_multiple:
            raise NotImplementedError("You may only deselect options of a multi-select")
        matched = False
        css = "option[value = %s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        for opt in opts:
            self._unsetSelected(opt)
            matched = True
        if not matched:
            raise NoSuchElementException("Could not locate element with value: %s" % value)
selector_builder.py 文件源码 项目:nerodia 作者: watir 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _given_xpath_or_css(self, selector):
        xpath = selector.pop('xpath', None)
        css = selector.pop('css', None)

        if not (xpath or css):
            return None

        if xpath and css:
            raise ValueError("'xpath' and 'css' cannot be combined ({})".format(selector))

        how, what = [None] * 2
        if xpath:
            how = By.XPATH
            what = xpath
        elif css:
            how = By.CSS_SELECTOR
            what = css

        if selector and not self._can_be_combined_with_xpath_or_css(selector):
            raise ValueError('{} cannot be combined with other selectors {})'.format(how, selector))

        return [how, what]
webelement.py 文件源码 项目:ShuoshuoMonitor 作者: aploium 项目源码 文件源码 阅读 22 收藏 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 项目源码 文件源码 阅读 24 收藏 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 项目源码 文件源码 阅读 32 收藏 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']
select.py 文件源码 项目:ShuoshuoMonitor 作者: aploium 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
            raise NoSuchElementException("Cannot locate option with value: %s" % value)
__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))
scene_marketing.py 文件源码 项目:pretix-screenshots 作者: pretix 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def shot_campaign(live_server, organizer, event, logged_in_client, campaign_web, campaign_twitter, orders, clicks):
    event.plugins += ',pretix_campaigns'
    event.save()

    logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/'.format(
        organizer.slug, event.slug
    ))
    screenshot(logged_in_client, 'website/control/campaigns_list.png')
    logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/{}/'.format(
        organizer.slug, event.slug, campaign_twitter.code
    ))
    WebDriverWait(logged_in_client, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#cbd_chart svg"))
    )
    time.sleep(.5)
    screenshot(logged_in_client, 'website/control/campaigns_detail.png')
scene_campaigns.py 文件源码 项目:pretix-screenshots 作者: pretix 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def shot_campaign(live_server, organizer, event, logged_in_client, campaign_web, campaign_twitter, orders, clicks):
    event.plugins += ',pretix_campaigns'
    event.save()

    logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/'.format(
        organizer.slug, event.slug
    ))
    screenshot(logged_in_client, 'plugins/campaigns/list.png')
    logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/{}/edit'.format(
        organizer.slug, event.slug, campaign_twitter.code
    ))
    screenshot(logged_in_client, 'plugins/campaigns/edit.png')

    logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/{}/'.format(
        organizer.slug, event.slug, campaign_twitter.code
    ))
    WebDriverWait(logged_in_client, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#cbd_chart svg"))
    )
    time.sleep(.5)
    screenshot(logged_in_client, 'plugins/campaigns/stats.png')
selenium.py 文件源码 项目:SerpScrap 作者: ecoron 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _goto_next_page(self):
        """
        Click the next page element,

        Returns:
            The url of the next page or False if there is no such url
                (end of available pages for instance).
        """
        next_url = ''
        element = self._find_next_page_element()

        if hasattr(element, 'click'):
            next_url = element.get_attribute('href')
            try:
                element.click()
            except WebDriverException:
                # See http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error
                # first move mouse to the next element, some times the element is not visibility
                selector = self.next_page_selectors[self.search_engine_name]
                if selector:
                    try:
                        next_element = WebDriverWait(self.webdriver, 5).until(
                            EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
                        webdriver.ActionChains(self.webdriver).move_to_element(next_element).perform()
                        # wait until the next page link emerges
                        WebDriverWait(self.webdriver, 8).until(
                            EC.visibility_of_element_located((By.CSS_SELECTOR, selector)))
                        element = self.webdriver.find_element_by_css_selector(selector)
                        next_url = element.get_attribute('href')
                        element.click()
                    except WebDriverException:
                        pass

        # wait until the next page was loaded

        if not next_url:
            return False
        else:
            return next_url
containerspage.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def choose_folder(self, folder_name):
        folder = self.is_object_present(folder_name)
        folder_link = folder.cells[0].find_element(By.CSS_SELECTOR, 'a')
        folder_link.click()
        self._wait_until(lambda _: self.objects_table.is_empty)


问题


面经


文章

微信
公众号

扫码关注公众号