Skip to content

Commit a1b0fbd

Browse files
committed
ruby: Escape selector when converting it to CSS
1 parent b099b4a commit a1b0fbd

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

rb/lib/selenium/webdriver/remote/w3c_bridge.rb

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -599,13 +599,13 @@ def convert_locators(how, what)
599599
case how
600600
when 'class name'
601601
how = 'css selector'
602-
what = ".#{what}"
602+
what = ".#{escape_css(what)}"
603603
when 'id'
604604
how = 'css selector'
605-
what = "##{what}"
605+
what = "##{escape_css(what)}"
606606
when 'name'
607607
how = 'css selector'
608-
what = "*[name='#{what}']"
608+
what = "*[name='#{escape_css(what)}']"
609609
when 'tag name'
610610
how = 'css selector'
611611
end
@@ -652,6 +652,20 @@ def escaper
652652
@escaper ||= defined?(URI::Parser) ? URI::Parser.new : URI
653653
end
654654

655+
ESCAPE_CSS_REGEXP = /(['"\\#.:;,!?+<>=~*^$|%&@`{}\-\[\]\(\)])/
656+
UNICODE_CODE_POINT = 30
657+
658+
# Escapes invalid characters in CSS selector.
659+
# @see https://mathiasbynens.be/notes/css-escapes
660+
def escape_css(string)
661+
string = string.gsub(ESCAPE_CSS_REGEXP) { |match| "\\#{match}" }
662+
if !string.empty? && string[0] =~ /[[:digit:]]/
663+
string = "\\#{UNICODE_CODE_POINT + Integer(string[0])} #{string[1..-1]}"
664+
end
665+
666+
string
667+
end
668+
655669
end # W3CBridge
656670
end # Remote
657671
end # WebDriver

0 commit comments

Comments
 (0)