【问题标题】:Accessing html generated by Javascript with htmlunit -Java使用 htmlunit -Java 访问 Javascript 生成的 html
【发布时间】:2011-02-27 01:33:49
【问题描述】:

我正在尝试测试一个使用 javascript 呈现大部分 HTML 的网站。使用 HTMLUNIT 浏览器,您将如何访问由 javascript 生成的 html?我正在查看他们的文档,但不确定最好的方法是什么。

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

这是获取页面 html 的简单方法,但是您会使用 domNode 还是其他方式来访问 javascript 生成的 html?

【问题讨论】:

    标签: java javascript html-parsing htmlunit


    【解决方案1】:

    你必须给 JavaScript 一些时间来执行。

    检查下面的示例工作代码。 bucketdivs 不在原始源中。

    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);
        }
    }
    

    输出:

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

    使用的 HtmlUnit 版本:

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

    【讨论】:

      【解决方案2】:

      假设问题是由于 AJAX 调用而由 JavaScript 生成的 HTML,您是否尝试过 'AJAX does not work' section in the HtmlUnit FAQ

      howtos about how to use HtmlUnit with JavaScript中还有一个部分。

      如果您的问题在这里没有得到解答,我想我们需要一些更具体的信息才能提供帮助。

      【讨论】:

        猜你喜欢
        • 2013-03-04
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-10
        • 1970-01-01
        相关资源
        最近更新 更多