Skip to content

Commit 7de30ca

Browse files
authored
Merge pull request #689 from dimaspivak/master
Use ConvertibleToCssTranslator in convert_css_to_xpath
2 parents 5bfd9f1 + be631e2 commit 7de30ca

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

seleniumbase/fixtures/css_to_xpath.py

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,49 @@
22
Convert CSS selectors into XPath selectors
33
"""
44

5-
from cssselect import GenericTranslator
5+
from cssselect.xpath import GenericTranslator, is_non_whitespace
6+
7+
8+
class ConvertibleToCssTranslator(GenericTranslator):
9+
"""An implementation of :py:class:`cssselect.GenericTranslator` with
10+
XPath output that more readily converts back to CSS selectors.
11+
The simplified examples in https://devhints.io/xpath were used as a
12+
reference here.
13+
"""
14+
def css_to_xpath(self, css, prefix='//'):
15+
return super(ConvertibleToCssTranslator, self).css_to_xpath(css,
16+
prefix)
17+
18+
def xpath_attrib_equals(self, xpath, name, value):
19+
xpath.add_condition('%s=%s' % (name, self.xpath_literal(value)))
20+
return xpath
21+
22+
def xpath_attrib_includes(self, xpath, name, value):
23+
if is_non_whitespace(value):
24+
xpath.add_condition(
25+
"contains(%s, %s)"
26+
% (name, self.xpath_literal(value)))
27+
else:
28+
xpath.add_condition('0')
29+
return xpath
30+
31+
def xpath_attrib_substringmatch(self, xpath, name, value):
32+
if value:
33+
# Attribute selectors are case sensitive
34+
xpath.add_condition('contains(%s, %s)' % (
35+
name, self.xpath_literal(value)))
36+
else:
37+
xpath.add_condition('0')
38+
return xpath
39+
40+
def xpath_class(self, class_selector):
41+
xpath = self.xpath(class_selector.selector)
42+
return self.xpath_attrib_equals(
43+
xpath, '@class', class_selector.class_name)
44+
45+
def xpath_descendant_combinator(self, left, right):
46+
"""right is a child, grand-child or further descendant of left"""
47+
return left.join('//', right)
648

749

850
def convert_css_to_xpath(css):
@@ -11,5 +53,5 @@ def convert_css_to_xpath(css):
1153
convert_css_to_xpath('button:contains("Next")')
1254
Output => "//button[contains(., 'Next')]"
1355
"""
14-
xpath = GenericTranslator().css_to_xpath(css, prefix='//')
56+
xpath = ConvertibleToCssTranslator().css_to_xpath(css)
1557
return xpath

0 commit comments

Comments
 (0)