Jsoup獲取動態js生成的內容

Jsoup本身是隻能獲取到靜態頁面的數據,並無法獲取動態生成的內容,所以單單使用jsoup是無法獲取到js生成的內容的。我這裏使用了htmlunit來獲取網頁內容後,將網頁轉換成xml格式,再通過jsoup進行解析

1.依賴導入

一般Jsoup和HttpClient都是一起使用的,版本隨意,可以無腦選擇新版本

    <dependencies>
        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

        <!--jsoup-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>

        <!--htmlunit-->
        <dependency>
            <groupId>net.sourceforge.htmlunit</groupId>
            <artifactId>htmlunit</artifactId>
            <version>2.33</version>
        </dependency>
    </dependencies>

2.簡單的代碼

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.*;

//使用Jsoup+Htmlunit下載動態js的內容
public class Test {

    public static void main(String[] args) throws IOException {
        //Htmlunit模擬的瀏覽器,設置css,js等支持及其它的一些簡單設置
        WebClient browser = new WebClient();
        browser.getOptions().setCssEnabled(false);
        browser.getOptions().setJavaScriptEnabled(true);
        browser.getOptions().setThrowExceptionOnScriptError(false);

        //獲取頁面
        HtmlPage htmlPage = browser.getPage("http://www.baidu.com");
        //設置等待js的加載時間
        browser.waitForBackgroundJavaScript(3000);

        //使用xml的方式解析獲取到jsoup的document對象
        Document doc = Jsoup.parse(htmlPage.asXml());
        System.out.println(doc);
    }



}

現在可以將獲取到的org.jsoup.nodes.Document使用Jsoup的方式進行解析了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章