我尝试使用javascriptexecutor计算xpath以获得WebElement列表。我可以用 (WebElement)jse.executeScript("return document.evaluate('//input[@name=\"q\"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;");
但当涉及到多个元素集时,就会抛出javascript错误。有人能帮我一下吗。这对我很有帮助。
我用来得到结果的代码
try{
Iterator<WebElement> arr=(Iterator<WebElement>)jse.executeScript("return document.evaluate('//a' ,document.body, null, XPathResult.ANY_TYPE, null)");
int count=0;
while(arr.hasNext()){
count=count+1;
}
System.out.println(count);
}catch(Exception e){
e.printStackTrace();
}
我用过所有类型的 XpathResult
关键词。
ANY_TYPE
UNORDERED_NODE_ITERATOR_TYPE
ORDERED_NODE_ITERATOR_TYPE
UNORDERED_NODE_SNAPSHOT_TYPE
ORDERED_NODE_SNAPSHOT_TYPE
ANY_UNORDERED_NODE_TYPE
堆栈跟踪错误
org.openqa.selenium.JavascriptException: javascript error: error reading property
(Session info: chrome=87.0.4280.88)
Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'
System info: host: 'DESKTOP-S3RV3MH', ip: '192.168.56.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 87.0.4280.88, chrome: {chromedriverVersion: 87.0.4280.88 (89e2380a3e36c..., userDataDir: C:\Users\DELL\AppData\Local...}, goog:chromeOptions: {debuggerAddress: localhost:61398}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
Session ID: 43d3c47a7d6d9419891c6948ef2398bd
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:537)
at demo.TestException.main(TestException.java:32)
1条答案
按热度按时间lrpiutwd1#
使用节点类型迭代器,将其添加到javascript数组中,然后返回:
示例代码: