1. 程式人生 > >HtmlUnit動態執行js函式

HtmlUnit動態執行js函式

功能:動態指定js函式,實際上這個效果不是很有用,這裡就做一個記錄而已,參考程式碼如下:

package com;
import com.gargoylesoftware.htmlunit.BrowserVersion;

import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.host.event.Event;
public class EBayHU {
	public static void main(String[] args) {
WebClient webClient = new WebClient(BrowserVersion.CHROME); //建立一個webclient           	        
    	webClient.getOptions().setJavaScriptEnabled(true); // 啟動JS	    	
    	webClient.getOptions().setUseInsecureSSL(true);//忽略ssl認證	    	
    	webClient.getOptions().setCssEnabled(false);//禁用Css,可避免自動二次請求CSS進行渲染	    	
		webClient.getOptions().setThrowExceptionOnScriptError(false);//執行錯誤時,不丟擲異常	    	
	    webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 設定Ajax非同步
	    try {
	    	HtmlPage page=webClient.getPage("url");
    		webClient.waitForBackgroundJavaScript(10000);
    		HtmlElement propic =page.getHtmlElementById("viEnlargeImgLayer_layer_fs");
	        DomNodeList<HtmlElement> picnodes=propic.getElementsByTagName("img");
	        for(int m=0;m<picnodes.size();m++){
	    		HtmlElement pic=picnodes.get(m);
	    		System.out.println(pic.asXml());
	    		//響應事件
	    		//Event event=new Event();
				//event.setEventType(Event.TYPE_KEY_DOWN);
				//HtmlPage hpm=pic.click(event); //bpic.fireEvent(event);
	    		//執行js	
	    		String hrefValue = "javascript:add(1,1,'+');";
	    		ScriptResult s = page.executeJavaScript(hrefValue);//執行js方法
	    		HtmlPage hpm=(HtmlPage) s.getNewPage();//獲得執行後的新page物件    	
	    		webClient.waitForBackgroundJavaScript(10000);
	    		HtmlElement lpic=hpm.getHtmlElementById("viEnlargeImgLayer_img_ctr");
	    		System.out.println(lpic.asXml());	    			   		
	        } 
    		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	 
	}