2
2
Convert CSS selectors into XPath selectors
3
3
"""
4
4
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 )
6
48
7
49
8
50
def convert_css_to_xpath (css ):
@@ -11,5 +53,5 @@ def convert_css_to_xpath(css):
11
53
convert_css_to_xpath('button:contains("Next")')
12
54
Output => "//button[contains(., 'Next')]"
13
55
"""
14
- xpath = GenericTranslator ().css_to_xpath (css , prefix = '//' )
56
+ xpath = ConvertibleToCssTranslator ().css_to_xpath (css )
15
57
return xpath
0 commit comments