Convert a css selector to an xpath, supporting pseudo elements.
435892
def css_to_func(css, flags, css_namespaces, lang):
    """"""
    from cssselect import parse, HTMLTranslator
    from cssselect.parser import FunctionalPseudoElement
    #  FIXME HACK need lessc to support functional-pseudo-selectors instead
    #  of marking as strings and stripping " here.
    if not (css):
        return None

    sel = parse(css.strip('" '))[0]
    xpath = HTMLTranslator().selector_to_xpath(sel)

    first_letter = False
    if sel.pseudo_element is not None:
        if type(sel.pseudo_element) == FunctionalPseudoElement:
            if sel.pseudo_element.name in ('attr', 'first-letter'):
                xpath += '/@' + sel.pseudo_element.arguments[0].value
                if sel.pseudo_element.name == 'first-letter':
                    first_letter = True
        elif isinstance(sel.pseudo_element, type(u'')):
            if sel.pseudo_element == 'first-letter':
                first_letter = True

    xp = etree.XPath(xpath, namespaces=css_namespaces)

    def toupper(u):
        """Use icu library for locale sensitive uppercasing (python2)."""
        loc = Locale(lang) if lang else Locale()
        return UnicodeString(u).toUpper(loc).encode('utf-8').decode('utf-8')

    def func(elem):
        res = xp(elem)
        if res:
            if etree.iselement(res[0]):
                res_str = etree.tostring(res[0], encoding='unicode',
                                         method="text")
            else:
                res_str = res[0]
            if first_letter:
                if res_str:
                    if flags and 'nocase' in flags:
                        return toupper(res_str[0])
                    else:
                        return res_str[0]
                else:
                    return res_str
            else:
                if flags and 'nocase' in flags:
                    return toupper(res_str)
                else:
                    return res_str

    return func
1225847
def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None):
        
        styles = Class()
        cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=validate)
        for rule in cssStyleSheet.cssRules:
            if rule.type==cssutils.css.CSSRule.FONT_FACE_RULE:
                if styles.get('@font-face') is None: styles['@font-face'] = []
                styles['@font-face'].append(Class.styleProperties(rule.style))
            
            elif rule.type==cssutils.css.CSSRule.IMPORT_RULE:
                if styles.get('@import') is None: styles['@import'] = []
                styles['@import'].append("url(%s)" % rule.href)

            elif rule.type==cssutils.css.CSSRule.NAMESPACE_RULE:
                if styles.get('@namespace') is None: styles['@namespace'] = {}
                styles['@namespace'][rule.prefix] = rule.namespaceURI
            
            elif rule.type==cssutils.css.CSSRule.MEDIA_RULE:
                if styles.get('@media') is None: styles['@media'] = []
                styles['@media'].append(rule.cssText)
            
            elif rule.type==cssutils.css.CSSRule.PAGE_RULE:
                if styles.get('@page') is None: styles['@page'] = []
                styles['@page'].append(rule.cssText)

            elif rule.type==cssutils.css.CSSRule.STYLE_RULE:
                for selector in rule.selectorList:
                    sel = selector.selectorText
                    if sel not in styles:
                        styles[sel] = Class.styleProperties(rule.style)
            
            elif rule.type==cssutils.css.CSSRule.CHARSET_RULE:
                styles['@charset'] = rule.encoding

            elif rule.type==cssutils.css.CSSRule.COMMENT:   # comments are thrown away
                pass

            elif rule.type==cssutils.css.CSSRule.VARIABLES_RULE:
                pass
            
            else:
                log.warning("Unknown rule type: %r" % rule.cssText)

        return styles
1368716
def find_element_by_xpath(self, xpath):
        
        from sdklib.html.elem import Elem5lib

        return Elem5lib(self.html_obj.find(self._convert_xpath(xpath)))
246495
def is_xpath_selector(selector):
    
    if (selector.startswith('/') or selector.startswith('./') or (
            selector.startswith('('))):
        return True
    return False
1257011
def _parseSimpleSelector(self, src):
        
        ctxsrc = src.lstrip()
        nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src)
        name, src = self._getMatchResult(self.re_element_name, src)
        if name:
            pass # already *successfully* assigned
        elif src[:1] in self.SelectorQualifiers:
            name = '*'
        else:
            raise self.ParseError('Selector name or qualifier expected', src, ctxsrc)

        name = self.cssBuilder.resolveNamespacePrefix(nsPrefix, name)
        selector = self.cssBuilder.selector(name)
        while src and src[:1] in self.SelectorQualifiers:
            hash_, src = self._getMatchResult(self.re_hash, src)
            if hash_ is not None:
                selector.addHashId(hash_)
                continue

            class_, src = self._getMatchResult(self.re_class, src)
            if class_ is not None:
                selector.addClass(class_)
                continue

            if src.startswith('['):
                src, selector = self._parseSelectorAttribute(src, selector)
            elif src.startswith(':'):
                src, selector = self._parseSelectorPseudo(src, selector)
            else:
                break

        return src.lstrip(), selector
575079
def _selector_as_string(self, selector):
        
        return ','.join(
            ''.join(token.as_css() for token in strip_whitespace(token_list))
            for token_list in split_on_comma(selector))
687223
function ( selector ) {
            var node = this.element().previousSibling;
            if ( !node ) return;
    
            //comment, text
            if ( node.nodeType == 8 || node.nodeType == 3 && !$B.string.trim(node.data) ) {
                return $B( node ).prev( selector );
            } else {
                if ( typeof selector === 'string' ) node = $B.selector.match( node, selector )? node : undefined;
                return node;
            }
        }
1341968
public function css($css, $context = null)
    {
        if ($css !== '' && $css[0] === '!') {
            $is_not = true;
            $css = substr($css, 1);
        } else {
            $is_not = false;
        }

        if ($pos = strpos($css, '::')) {
            $xpath = $this->_cssToXPath->transform(substr($css, $pos + 2));
            $xpath = substr($css, 0, $pos + 2) . substr($xpath, 2);
        } else {
            $xpath = $this->_cssToXPath->transform($css);
        }

        if ($context && $xpath[0] === '/') {
            $xpath = '.' . $xpath;
        }

        return $this->xpath($is_not ? "not($xpath)" : $xpath, $context);
    }
422320
def parse(self, src):
        """"""

        self.cssBuilder.beginStylesheet()
        try:

            # XXX Some simple preprocessing
            src = cssSpecial.cleanupCSS(src)

            try:
                src, stylesheet = self._parseStylesheet(src)
            except self.ParseError as err:
                err.setFullCSSSource(src)
                raise
        finally:
            self.cssBuilder.endStylesheet()
        return stylesheet
157783
def parse_tag_pattern(self, sel, m, has_selector):
        """"""

        parts = [css_unescape(x) for x in m.group(0).split('|')]
        if len(parts) > 1:
            prefix = parts[0]
            tag = parts[1]
        else:
            tag = parts[0]
            prefix = None
        sel.tag = ct.SelectorTag(tag, prefix)
        has_selector = True
        return has_selector
1336668
def find_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
        
        self.wait_for_ready_state_complete()
        if page_utils.is_xpath_selector(selector):
            by = By.XPATH
        if page_utils.is_link_text_selector(selector):
            selector = page_utils.get_link_text_from_selector(selector)
            by = By.LINK_TEXT
        elements = self.driver.find_elements(by=by, value=selector)
        if limit and limit > 0 and len(elements) > limit:
            elements = elements[:limit]
        return elements
1357325
private List<String> parseSelector() {
        List<String> selector = new ArrayList<>();
        parseSelectorPrefix(selector);

        while (tokenizer.more()) {
            if (tokenizer.current().isSymbol("{", ",")) {
                if (selector.isEmpty()) {
                    tokenizer.addError(tokenizer.current(), "Unexpected end of CSS selector");
                }

                return selector;
            } else if (tokenizer.current().isIdentifier()
                       || tokenizer.current().isSpecialIdentifier("#", "@")
                       || tokenizer.current().isNumber()) {
                StringBuilder sb = new StringBuilder(tokenizer.consume().getSource());
                parseFilterInSelector(sb);
                parseOperatorInSelector(sb);
                selector.add(sb.toString());
            } else if (tokenizer.current().isSymbol("&") || tokenizer.current().isSymbol("*")) {
                selector.add(tokenizer.consume().getTrigger());
            } else if (tokenizer.current().isSymbol(">", "+", "~")) {
                selector.add(tokenizer.consume().getSource());
            } else {
                tokenizer.addError(tokenizer.current(), "Unexpected Token: %s", tokenizer.consume().getSource());
            }
        }
        return selector;
    }
661611
def parse_pseudo_lang(self, sel, m, has_selector):
        """"""

        values = m.group('values')
        patterns = []
        for token in RE_VALUES.finditer(values):
            if token.group('split'):
                continue
            value = token.group('value')
            if value.startswith(('"', "'")):
                parts = css_unescape(value[1:-1], True).split('-')
            else:
                parts = css_unescape(value).split('-')

            new_parts = []
            first = True
            for part in parts:
                if part == '*' and first:
                    new_parts.append('(?!x\b)[a-z0-9]+?')
                elif part != '*':
                    new_parts.append(('' if first else '(-(?!x\b)[a-z0-9]+)*?\\-') + re.escape(part))
                if first:
                    first = False
            patterns.append(re.compile(r'^{}(?:-.*)?$'.format(''.join(new_parts)), re.I))
        sel.lang.append(ct.SelectorLang(patterns))
        has_selector = True

        return has_selector
48218
function eval_css(locator, inDocument) {
    var results = [];
    try {
      window.Sizzle(locator, inDocument, results);
    } catch (ignored) {
      // Presumably poor formatting
    }
    return results;
}
100705
function (elem)
    {
        var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue;
        if (elem.nodeType == Strophe.ElementType.NORMAL) {
            tag = elem.nodeName;
            if(Strophe.XHTML.validTag(tag)) {
                try {
                    el = Strophe.xmlElement(tag);
                    for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
                        attribute = Strophe.XHTML.attributes[tag][i];
                        value = elem.getAttribute(attribute);
                        if(typeof value == 'undefined' || value === null || value === '' || value === false || value === 0) {
                            continue;
                        }
                        if(attribute == 'style' && typeof value == 'object') {
                            if(typeof value.cssText != 'undefined') {
                                value = value.cssText; // we're dealing with IE, need to get CSS out
                            }
                        }
                        // filter out invalid css styles
                        if(attribute == 'style') {
                            css = [];
                            cssAttrs = value.split(';');
                            for(j = 0; j < cssAttrs.length; j++) {
                                attr = cssAttrs[j].split(':');
                                cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
                                if(Strophe.XHTML.validCSS(cssName)) {
                                    cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
                                    css.push(cssName + ': ' + cssValue);
                                }
                            }
                            if(css.length > 0) {
                                value = css.join('; ');
                                el.setAttribute(attribute, value);
                            }
                        } else {
                            el.setAttribute(attribute, value);
                        }
                    }

                    for (i = 0; i < elem.childNodes.length; i++) {
                        el.appendChild(Strophe.createHtml(elem.childNodes[i]));
                    }
                } catch(e) { // invalid elements
                  el = Strophe.xmlTextNode('');
                }
            } else {
                el = Strophe.xmlGenerator().createDocumentFragment();
                for (i = 0; i < elem.childNodes.length; i++) {
                    el.appendChild(Strophe.createHtml(elem.childNodes[i]));
                }
            }
        } else if (elem.nodeType == Strophe.ElementType.FRAGMENT) {
            el = Strophe.xmlGenerator().createDocumentFragment();
            for (i = 0; i < elem.childNodes.length; i++) {
                el.appendChild(Strophe.createHtml(elem.childNodes[i]));
            }
        } else if (elem.nodeType == Strophe.ElementType.TEXT) {
            el = Strophe.xmlTextNode(elem.nodeValue);
        }

        return el;
    }
265206
def isolcss(prefix, css):
    
    try:
        # Attempt full strict parse, raise exception on failure.
        all(True for m in matchiter(selrule_or_atom_re, css))
    except ValueError as e:
        logger.warning("Strict parse failed at char {}".format(e.args[0]))
        splits = matchiter(selrule_or_any_re, css)
    else:
        splits = matchiter(selrule_or_atom_re, css)

    css = []

    for m in splits:
        if not m.groupdict()['sels']:
            css.extend(m.group(0))
            continue

        sels = matchall(sel_re, m.group('sels'))

        # This should never happen because sel_re is a subpattern
        # of the original match.
        assert sels, "Failed to split selectors: {!r}".format(m.group('sels'))

        for sel in sels:
            atoms = matchall(atom_re, sel)
            if '&' in atoms:
                sel = ''.join((prefix if a == '&' else a) for a in atoms)
            else:
                sel = '%s %s' % (prefix, sel)
            css.append(sel)
        css.append(m.group('ruleset'))

    return ''.join(css)
164214
def find_elements_by_xpath(self, xpath):
        
        from sdklib.html.elem import Elem5lib

        return [Elem5lib(e) for e in self.html_obj.findall(self._convert_xpath(xpath))]