use*_*009 2 css java selenium xpath
作为我测试的一部分,系统应该查明用于打开网站的设备是移动设备还是普通桌面.
我一直收到错误:
"InvalidSelectorError:无法找到带有xpath表达式的元素//*[contains(@class,is-mobile ..."
萤火虫的财产:
<body class="login-page is-desktop">
Run Code Online (Sandbox Code Playgroud)
我的测试:
public class isMobile {
public static boolean isMobile = false;
public static boolean checkIfMobile(WebDriver driver) throws Exception {
List<WebElement> list = driver.findElements(By
.xpath("//body[contains(@class, 'is-mobile'"));
if (list == null) {
return false;
} else {
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我正确的XPath应该如何?
Mos*_*cho 10
你似乎错过了收盘和方括号:
改变这个:
//body[contains(@class, 'is-mobile'
Run Code Online (Sandbox Code Playgroud)
进入:
//body[contains(@class, 'is-mobile')]
Run Code Online (Sandbox Code Playgroud)
作为旁注,请注意此代码有另一个稍微隐藏的问题,并且您将匹配您不想匹配的内容,例如此类属性:login-page not-is-mobile.
没有办法简单地匹配,就像使用CSS3选择器一样[class~="is-mobile"].但是,你可以通过这样做来解决这个问题:
//body[contains(concat(' ', @class, ' '), ' is-mobile ')]
Run Code Online (Sandbox Code Playgroud)
所有这些空格都是为了确保你只匹配空格之间的东西,即使它在class属性的开头或结尾也匹配.
这确实是丑陋的,但这是XPath的做法.