Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for :has(<relative operator>) #115

Merged
merged 18 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions cssselect/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,30 @@ def specificity(self):
return a1 + a2, b1 + b2, c1 + c2


class Relation(object):
"""
Represents selector:has(subselector)
"""
def __init__(self, selector, subselector):
self.selector = selector
self.subselector = subselector

def __repr__(self):
return '%s[%r:has(%r)]' % (
self.__class__.__name__, self.selector, self.subselector)

def canonical(self):
subsel = self.subselector.canonical()
if len(subsel) > 1:
subsel = subsel.lstrip('*')
return '%s:has(%s)' % (self.selector.canonical(), subsel)

def specificity(self):
a1, b1, c1 = self.selector.specificity()
a2, b2, c2 = self.subselector.specificity()
return a1 + a2, b1 + b2, c1 + c2


class Attrib(object):
"""
Represents selector[namespace|attrib operator value]
Expand Down Expand Up @@ -538,6 +562,9 @@ def parse_simple_selector(stream, inside_negation=False):
if next != ('DELIM', ')'):
raise SelectorSyntaxError("Expected ')', got %s" % (next,))
result = Negation(result, argument)
elif ident.lower() == 'has':
arguments = parse_relative_selector(stream)
result = Relation(result, arguments)
else:
result = Function(result, ident, parse_arguments(stream))
else:
Expand All @@ -564,6 +591,24 @@ def parse_arguments(stream):
"Expected an argument, got %s" % (next,))


def parse_relative_selector(stream):
arguments = []
stream.skip_whitespace()
next = stream.next()
if next in [('DELIM', '+'), ('DELIM', '-'), ('DELIM', '>'), ('DELIM', '~')]:
arguments.append(next)
annbgn marked this conversation as resolved.
Show resolved Hide resolved
while 1:
stream.skip_whitespace()
next = stream.next()
if next.type in ('IDENT', 'STRING', 'NUMBER'):
arguments.append(Element(element=next.value))
elif next == ('DELIM', ')'):
return arguments
else:
raise SelectorSyntaxError(
"Expected an argument, got %s" % (next,))


def parse_attrib(selector, stream):
stream.skip_whitespace()
attrib = stream.next_ident_or_star()
Expand Down
6 changes: 6 additions & 0 deletions cssselect/xpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,12 @@ def xpath_negation(self, negation):
else:
return xpath.add_condition('0')

def xpath_relation(self, relation):
xpath = self.xpath(relation.selector)
combinator, subselector, *_ = relation.subselector
wRAR marked this conversation as resolved.
Show resolved Hide resolved
method = getattr(self, 'xpath_%s_combinator' % self.combinator_mapping[combinator.value])
return method(xpath, self.xpath(subselector))

def xpath_function(self, function):
"""Translate a functional pseudo-class."""
method = 'xpath_%s_function' % function.name.replace('-', '_')
Expand Down
17 changes: 17 additions & 0 deletions tests/test_cssselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,13 @@ def specificity(css):
assert specificity(':not(:empty)') == (0, 1, 0)
assert specificity(':not(#foo)') == (1, 0, 0)

# assert specificity(':has(*)') == (0, 0, 0)
# assert specificity(':has(foo)') == (0, 0, 1)
# assert specificity(':has(.foo)') == (0, 1, 0)
# assert specificity(':has([foo])') == (0, 1, 0)
# assert specificity(':has(:empty)') == (0, 1, 0)
# assert specificity(':has(#foo)') == (1, 0, 0)

assert specificity('foo:empty') == (0, 1, 1)
assert specificity('foo:before') == (0, 0, 2)
assert specificity('foo::before') == (0, 0, 2)
Expand Down Expand Up @@ -300,6 +307,12 @@ def css2css(css, res=None):
css2css(':not(*[foo])', ':not([foo])')
css2css(':not(:empty)')
css2css(':not(#foo)')
# css2css(':has(*)')
# css2css(':has(foo)')
# css2css(':has(*.foo)', ':has(.foo)')
# css2css(':has(*[foo])', ':has([foo])')
# css2css(':has(:empty)')
# css2css(':has(#foo)')
css2css('foo:empty')
css2css('foo::before')
css2css('foo:empty::before')
Expand Down Expand Up @@ -492,6 +505,7 @@ def xpath(css):
"e[not(count(preceding-sibling::*) mod 2 = 0)]")
assert xpath('e:nOT(*)') == (
"e[0]") # never matches
assert xpath('e:has(> f)') == 'e/f'
elacuesta marked this conversation as resolved.
Show resolved Hide resolved
assert xpath('e f') == (
"e/descendant-or-self::*/f")
assert xpath('e > f') == (
Expand Down Expand Up @@ -863,6 +877,9 @@ def pcss(main, *selectors, **kwargs):
assert pcss('ol :Not(li[class])') == [
'first-li', 'second-li', 'li-div',
'fifth-li', 'sixth-li', 'seventh-li']
# assert pcss('link:has(*)') == []
# assert pcss('link:has([href])') == ['link-href']
# assert pcss('ol:has(div)') == ['first-ol']
assert pcss('ol.a.b.c > li.c:nth-child(3)') == ['third-li']

# Invalid characters in XPath element names, should not crash
Expand Down