首页 > 解决方案 > 为什么 Selenium 在连字符之前插入反斜杠?

问题描述

以下代码在IEFirefox中失败。Chrome 从来没有遇到过问题。

foundElement = driver.FindElement(By.Id("btn-GDR"));

它说找不到元素#btn\-GDR

为什么Selenium\在之前插入 a -

火狐 65.0.2 版本 IE 11.0.9600.19301

编辑:更多信息:我试过使用

"btn\x2dGDR" 表示 \x2d 是 "-" 符号(十六进制中的 ASCII),但它不能解决问题。它总是在它前面插入一个“\”。

标签: regexseleniumselenium-webdrivercss-selectorswebdriver

解决方案


As Selenium converts the different Locator Strategies into it's effective CSS selectors as per the switch - cases the values of class name, id, name, tag name, etc are converted through:

cssEscape(value);

The cssEscape(value) is defined as:

private String cssEscape(String using) {
  using = using.replaceAll("([\\s'\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-\\/\\[\\]\\(\\)])", "\\\\$1");
  if (using.length() > 0 && Character.isDigit(using.charAt(0))) {
    using = "\\" + Integer.toString(30 + Integer.parseInt(using.substring(0,1))) + " " + using.substring(1);
  }
  return using;
}

Hence you see the - character being escaped by the \ character.


推荐阅读