[英]Unable to handle alert using phantomJS in Java
我有一個Java代碼,如下所示,當我通過PhantomJs運行得到“不支持的命令異常”,但如果我運行firefox和chrome,它工作正常: -
注意:使用phantomJs,我們可以在下面的代碼中執行到第3步。我在許多博客中搜索,但這些答案並沒有解決我的問題。
1. cvvField.sendKeys(cvcData);
2. proceedToPayBtn.click();
3. Reporter.log("Card details are submitted from payment UI page");
4. Alert a1=driver.switchTo().alert();
5. Reporter.log("Alert with text:"+a1.getText());
6. a1.accept();
這里cvvField和proceedToPayBtn是WebElements,cvcData的值為“111”。
錯誤日志: -
org.openqa.selenium.UnsupportedCommandException: Invalid Command Method -
{"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","Host":"localhost:30462","User-Agent":"Apache-HttpClient/4.5.1 (Java/1.8.0_101)"},"httpVersion":"1.1","method":"GET","url":"/alert_text","urlParsed":{"anchor":"","query":"","file":"alert_text","directory":"/","path":"/alert_text","relative":"
/alert_text","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/alert_text","queryKey":{},"chunks":["alert_text"]},"urlOriginal":"/session/9e392a50-ce79-11e6-b24a-2b12cf1ec4d6/alert_text"}
命令持續時間或超時: 31 milliseconds
我已編輯上面的代碼如下,但同樣的錯誤即將到來。請建議
if (driver instanceof PhantomJSDriver)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.alert = function(){};");
je.executeScript("window.confirm = function(){return true;};");
System.out.println("Alert has been handled");
} else {
Alert a1 = driver.switchTo().alert();
a1.accept();
}
我在輸出控制台中收到“已處理警報”但未處理警報。
由於等待時間的一些問題可能是您的問題的根源上面的代碼可以幫助等待元素可見(因為ngWebDriver或Selenium Webdriver的等待與PhantomJS不兼容)
public static String waitJSResponse(PhantomJSDriver driver, String script) {
String ReturnedValue = null;
int sleeper = 10;
Boolean flag = false;
int timeOut = 30000;
int i = 0;
while ((!flag) & ((i*sleeper)<timeOut)) {
try {
Thread.sleep(sleeper);
ReturnedValue = (String) driver.executeScript(script);
} catch (Exception e) {
flag = false;
i++;
}
if (ReturnedValue != null) {
flag = true;
System.out.println("Overall wait time is : "+(i * sleeper)+" ms \n\r");
break;
}
}
return ReturnedValue;
}
此代碼將等待10毫秒,然后驗證元素是否可見,如果有異常,它將再次循環。 返回的值必須是文本,對象或非空的任何內容。 腳本值必須是您的JS腳本才能獲得正確的元素。
希望它有效。
我嘗試了上面的代碼: -
1.創建一個“測試”類並在其中編寫上述方法。 2.Above方法通過創建一個對象(TestObject)來調用
TestObject.waitJSResponse((PhantomJSDriver)驅動程序,“window.confirm = function(){return true;};”);
但是返回值在
try
{
Thread.sleep(sleeper);
ReturnedValue = (String) driver.executeScript(script);
System.out.println(ReturnedValue);
}
返回null.So你能幫忙嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.