2010-06-02 5 views
11

J'essaie de pouvoir tester un site web qui utilise javascript pour afficher la plus grande partie du HTML. Avec le navigateur HTMLUNIT, comment seriez-vous capable d'accéder au html généré par le javascript? Je regardais leur documentation mais je ne savais pas quelle serait la meilleure approche.Accéder à html généré par Javascript avec htmlunit -Java

WebClient webClient = new WebClient(); 
HtmlPage currentPage = webClient.getPage("some url"); 
String Source = currentPage.asXml(); 
System.out.println(Source); 

Ceci est un moyen facile de récupérer le code HTML de la page, mais utiliseriez-vous le domNode ou d'une autre façon d'accéder au code HTML généré par le javascript?

Répondre

9

Vous devez donner du temps pour l'exécution de JavaScript.

Vérifiez un exemple de code de travail ci-dessous. Les bucketdiv ne sont pas dans la source d'origine.

import java.io.IOException; 
import java.net.MalformedURLException; 
import java.util.List; 
import com.gargoylesoftware.htmlunit.*; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 

public class GetPageSourceAfterJS { 
    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException { 
     java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF); /* comment out to turn off annoying htmlunit warnings */ 
     WebClient webClient = new WebClient(); 
     String url = "http://www.futurebazaar.com/categories/Home--Living-Luggage--Travel-Airbags--Duffel-bags/cid-CU00089575.aspx"; 
     System.out.println("Loading page now: "+url); 
     HtmlPage page = webClient.getPage(url); 
     webClient.waitForBackgroundJavaScript(30 * 1000); /* will wait JavaScript to execute up to 30s */ 

     String pageAsXml = page.asXml(); 
     System.out.println("Contains bucket? --> "+pageAsXml.contains("bucket")); 

     //get divs which have a 'class' attribute of 'bucket' 
     List<?> buckets = page.getByXPath("//div[@class='bucket']"); 
     System.out.println("Found "+buckets.size()+" 'bucket' divs."); 

     //System.out.println("#FULL source after JavaScript execution:\n "+pageAsXml); 
    } 
} 

Sortie:

Loading page now: http://www.futurebazaar.com/categories/Mobiles-Mobile-Phones/cid-CU00089697.asp‌​x?Rfs=brandZZFly001PYXQcurtrayZZBrand 
Contains bucket? --> true 
Found 3 'bucket' divs. 

version HtmlUnit utilisé:

<dependency> 
    <groupId>net.sourceforge.htmlunit</groupId> 
    <artifactId>htmlunit</artifactId> 
    <version>2.12</version> 
</dependency> 
Questions connexes