我正在尝试使用selenium自动化表单提交。但是,点击登录时运行的JavaScript会导致异常调用提交。 Selenium将提交指向localhost,而不是表单操作。任何人都可以解释为什么会发生这种情况并善意地提供解决方案来解决这个问题。
以下是表格:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Sign On</title>
<base href="https://machine.place.domain.com:9031/"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" type="text/css" href="assets/css/main.css"/>
</head>
<body onload="setFocus()">
<div class="container signin">
<div class="header">
Sign On
</div>
<div class="body-container">
<div class="section-title">
Please sign on and we'll send you right along.
</div>
<div>
<form method="POST" action="/idp/L0YZK/resumeSAML20/idp/SSO.ping" autocomplete="off">
<div class="messages">
</div>
<div class="input-label">
Username
</div>
<div class="input-container">
<input id="username" type="text" size="36" name="pf.username" value="" autocorrect="off" autocapitalize="off" onKeyPress="return postOnReturn(event)" placeholder="Username" /><!---->
</div>
<div class="input-label">
Password
</div>
<div class="input-container">
<input id="password" type="password" size="36" name="pf.pass" onKeyPress="return postOnReturn(event)" placeholder="Password" />
</div>
<div class="buttons">
<input type="hidden" name="pf.ok" value=""/>
<input type="hidden" name="pf.cancel" value=""/>
<a href="javascript:void(0)" onclick="postCancel();" class="button blue deny" title="Cancel">
Cancel
</a>
<a href="javascript:void(0)" onclick="postOk();" class="button normal allow" title="Sign On">
Sign On
</a>
</div>
</form>
</div>
</div>
<div class="footer-container">
<div class="footer">
<div class="credits">
<a href="http://www.example.com">Example</a>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function postOk() {
document.forms[0]['pf.ok'].value = 'clicked';
document.forms[0].submit();
}
function postCancel() {
document.forms[0]['pf.cancel'].value = 'clicked';
document.forms[0].submit();
}
function postOnReturn(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
document.forms[0].submit();
return false;
} else {
return true;
}
}
function setFocus() {
var platform = navigator.platform;
if(platform != null && platform.indexOf("iPhone") == -1) {
document.getElementById('username').focus();
}
}
function setMobile(mobile) {
var className = ' mobile',
hasClass = (bodyTag.className.indexOf(className) !== -1);
if(mobile && !hasClass) {
bodyTag.className += className;
} else if (!mobile && hasClass) {
bodyTag.className = bodyTag.className.replace(className, '');
}
}
function getScreenWidth() {
return (window.outerHeight) ? window.outerWidth : document.body.clientWidth;
}
var bodyTag = document.getElementsByTagName('body')[0],
width = getScreenWidth(),
remember = false && false;
if(/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
setMobile(true);
} else {
setMobile((width <= 480));
window.onresize = function() {
width = getScreenWidth();
setMobile((width <= 480));
}
}
</script>
</body>
</html>
这是我的Java代码:
private final static String PF_BASE_URL = "https://machine.place.domain.com";
private final static String PF_PRIMARY_SSL_PORT = "9031";
private final static String PF_START_SSO_ENDPOINT = "/sp/startSSO.ping";
private final static String PARTNER_ENTITY_ID = "LDAPTest:SAML2:IDP";
try{
DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
capability.setJavascriptEnabled(true);
WebDriver driver = new HtmlUnitDriver(capability);
driver.get(PF_BASE_URL + ":" + PF_PRIMARY_SSL_PORT + PF_START_SSO_ENDPOINT + "?" + "PartnerIdpId="+ PARTNER_ENTITY_ID);
HtmlUnitWebElement formElement = (HtmlUnitWebElement) driver.findElement(By.tagName("form"));
String actionURL = formElement.getAttribute("action");
String newactionURL = PF_BASE_URL + ":" + PF_PRIMARY_SSL_PORT + actionURL;
String script = "document.forms[0].action='"+newactionURL+"'";
if(driver instanceof JavascriptExecutor){
((JavascriptExecutor) driver).executeScript(script);
}
HtmlUnitWebElement usernameElement = (HtmlUnitWebElement) driver.findElement(By.id("username"));
usernameElement.sendKeys("user");
HtmlUnitWebElement passwordElement = (HtmlUnitWebElement) driver.findElement(By.id("password"));
passwordElement.sendKeys("password");
List<WebElement> anchors = driver.findElements(By.tagName("a"));
for (int i = 0; i < anchors.size(); i++) {
String title = anchors.get(i).getAttribute("title");
if (title.equalsIgnoreCase("Sign on")) {
anchors.get(i).click();
break;
}
}
driver.close();
} catch (Exception e){
System.out.println(e.tostring());
}
这是stacktrace:
Exception in thread "main" org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: Exception invoking submit
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 03:03:16'
System info: host: '********', ip: '***********', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_40'
Driver info: driver.version: HtmlUnitDriver
at org.openqa.selenium.htmlunit.HtmlUnitDriver.executeScript(HtmlUnitDriver.java:683)
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.submitForm(HtmlUnitWebElement.java:213)
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.submit(HtmlUnitWebElement.java:166)
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.submit(HtmlUnitWebElement.java:184)
at WasteClass.main(WasteClass.java:61)
Caused by: com.gargoylesoftware.htmlunit.ScriptException: Exception invoking submit
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:847)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:779)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:751)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:1008)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.executeScript(HtmlUnitDriver.java:677)
... 4 more
Caused by: com.gargoylesoftware.htmlunit.ScriptException: Exception invoking submit
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:847)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:779)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:751)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:1008)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeEventHandler(EventListenersContainer.java:234)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeBubblingListeners(EventListenersContainer.java:254)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.fireEvent(EventTarget.java:186)
at com.gargoylesoftware.htmlunit.html.HtmlElement$1.run(HtmlElement.java:923)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.html.HtmlElement.fireEvent(HtmlElement.java:928)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1316)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:286)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:478)
at com.gargoylesoftware.htmlunit.WebClient.loadDownloadedResponses(WebClient.java:2110)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.doProcessPostponedActions(JavaScriptEngine.java:875)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.access$500(JavaScriptEngine.java:104)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:842)
... 10 more
Caused by: com.gargoylesoftware.htmlunit.ScriptException: Exception invoking submit
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:847)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:779)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:751)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:1008)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeEventHandler(EventListenersContainer.java:234)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventListenersContainer.executeBubblingListeners(EventListenersContainer.java:254)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget.fireEvent(EventTarget.java:186)
at com.gargoylesoftware.htmlunit.html.HtmlElement$1.run(HtmlElement.java:923)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.html.HtmlElement.fireEvent(HtmlElement.java:928)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeEventHandlersIfNeeded(HtmlPage.java:1316)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:286)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:478)
at com.gargoylesoftware.htmlunit.WebClient.loadDownloadedResponses(WebClient.java:2110)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.doProcessPostponedActions(JavaScriptEngine.java:875)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.access$500(JavaScriptEngine.java:104)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:842)
... 29 more
Caused by: java.lang.RuntimeException: Exception invoking submit
at net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:181)
at net.sourceforge.htmlunit.corejs.javascript.FunctionObject.call(FunctionObject.java:449)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1536)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:798)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at com.gargoylesoftware.htmlunit.javascript.host.event.EventHandler.call(EventHandler.java:82)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:411)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:309)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3286)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$4.doRun(JavaScriptEngine.java:772)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:832)
... 48 more
Caused by: java.lang.RuntimeException: org.apache.http.conn.HttpHostConnectException: Connect to localhost:80 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at com.gargoylesoftware.htmlunit.WebClient.download(WebClient.java:2054)
at com.gargoylesoftware.htmlunit.javascript.host.html.HTMLFormElement.submit(HTMLFormElement.java:355)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:153)
... 58 more
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:80 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:184)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1316)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1233)
at com.gargoylesoftware.htmlunit.WebClient.download(WebClient.java:2050)
... 64 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134)
... 76 more