Jsoup本身是只能獲取到靜態(tài)頁面的數(shù)據(jù),并無法獲取動態(tài)生成的內(nèi)容,所以單單使用jsoup是無法獲取到j(luò)s生成的內(nèi)容的。我這里使用了htmlunit來獲取網(wǎng)頁內(nèi)容后,將網(wǎng)頁轉(zhuǎn)換成xml格式,再通過jsoup進(jìn)行解析
1.依賴導(dǎo)入
一般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下載動態(tài)js的內(nèi)容
public class Test {
public static void main(String[] args) throws IOException {
//Htmlunit模擬的瀏覽器,設(shè)置css,js等支持及其它的一些簡單設(shè)置
WebClient browser = new WebClient();
browser.getOptions().setCssEnabled(false);
browser.getOptions().setJavaScriptEnabled(true);
browser.getOptions().setThrowExceptionOnScriptError(false);
//獲取頁面
HtmlPage htmlPage = browser.getPage("http://www.baidu.com");
//設(shè)置等待js的加載時間
browser.waitForBackgroundJavaScript(3000);
//使用xml的方式解析獲取到j(luò)soup的document對象
Document doc = Jsoup.parse(htmlPage.asXml());
System.out.println(doc);
}
}
現(xiàn)在可以將獲取到的org.jsoup.nodes.Document使用Jsoup的方式進(jìn)行解析了!