如何解决Selenium NoSuchElementException:无法使用RemoteWebDriver Java使用By.xpath定位元素
在本地计算机上运行拖放文件上载脚本可以正常工作并通过测试,但是当尝试远程运行相同脚本-RemoteWebDriver时,测试失败,但出现以下例外:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:
{"method":"xpath","selector":"//*[@class='dz-message']"}
(Session info: chrome=62.0.3202.75)
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT
6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 50 milliseconds
For documentation on this error,please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.1',revision: 'a36b8b1',time: '2016-06-30 17:37:03'
System info: host: 'vc2coma1395994',ip: '10.146.2.48',os.name: 'Windows Server 2012 R2',os.arch:
'amd64',os.version: '6.3',java.version: '1.8.0_211'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false,rotatable=false,mobileEmulationEnabled=false,
我尝试使用显式等待,但无济于事
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@class='dz message']")));
这是代码 driver.get(“ http://html5demos.com/file-api”); WebElement droparea = driver.findElement(By.cssSelector(“#holder”));
@FindBy(how = How.XPATH,using = "//*[@class='dz-message']")
private WebElement target;
public void dropFile(String filePath){
File file = new File(filePath);
int offsetX =0,offsetY=0;
if(!file.exists())
throw new WebDriverException("File not found: " +
file.toString());
JavascriptExecutor jse = (JavascriptExecutor)driver;
WebDriverWait wait = new WebDriverWait(driver,30);
String JS_DROP_FILE =
"var target = arguments[0]," +
" offsetX = arguments[1]," +
" offsetY = arguments[2]," +
" document = target.ownerDocument || document," +
" window = document.defaultView || window;" +
"" +
"var input = document.createElement('INPUT');" +
"input.type = 'file';" +
"input.style.display = 'none';" +
"input.onchange = function () {" +
" var rect = target.getBoundingClientRect()," +
" x = rect.left + (offsetX || (rect.width >> 1))," +
" y = rect.top + (offsetY || (rect.height >> 1))," +
" dataTransfer = { files: this.files };" +
"" +
" ['dragenter','dragover','drop'].forEach(function (name) {" +
" var evt = document.createEvent('MouseEvent');" +
" evt.initMouseEvent(name,!0,window,x,y,!1,null);" +
" evt.dataTransfer = dataTransfer;" +
" target.dispatchEvent(evt);" +
" });" +
"" +
" setTimeout(function () { document.body.removeChild(input); },25);" +
"};" +
"document.body.appendChild(input);" +
"return input;";
WebElement input = (WebElement)jse.executeScript(JS_DROP_FILE,target,offsetX,offsetY);
input.sendKeys(file.getAbsoluteFile().toString());
wait.until(ExpectedConditions.stalenessOf(input));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。