我正在尝试这段代码:
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.JavaScriptPage;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLScriptElement;
import java.net.URL;
import java.util.List;
public class Example {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_6);
URL url=new URL("http://www.google.com");
WebRequest request= new WebRequest(url);
WebResponse response=new WebResponse(null, request, 6000);
webClient.setJavaScriptEnabled(true);
webClient.setThrowExceptionOnScriptError(false);
webClient.setCssEnabled(false);
webClient.setRedirectEnabled(true);
JavaScriptEngine engine = new JavaScriptEngine(webClient);
webClient.setJavaScriptEngine(engine);
HtmlPage firstPage = null;
ScriptResult result = null;
JavaScriptPage jsp=new JavaScriptPage(response, null);
try {
firstPage = webClient.getPage(request);
} catch (Exception e) {
e.printStackTrace();
}
String JavaScriptCode = "1+1";
try {
result = firstPage.executeJavaScript(JavaScriptCode);
} catch (Exception e) {
e.printStackTrace();
}
Object javaScriptResult = result.getJavaScriptResult();
System.out.println(javaScriptResult);
}
}
它适用于简单的JavaScript代码,例如"1+1"
。我想执行在URL的页面源中定义的特定函数。
URL是我在此代码中定义的字段。
答案 0 :(得分:4)
这是一个工作示例,我试图让它变得尽可能简单:
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class Test {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage page = webClient.getPage("http://www.iana.org/");
String javaScriptCode = "inArray([1,2],3)";
Object result = page.executeJavaScript(javaScriptCode).getJavaScriptResult();
System.out.println(result);
}
}