嘗試使用HtmlUnit來渲染頁面(包括JavaScript和CSS DOM操作),然後通過HTML渲染到jsoup。
// load page using HTML Unit and fire scripts
WebClient webClient = new WebClient();
HtmlPage myPage = webClient.getPage(myURL);
// convert page to generated HTML and convert to document
Document doc = Jsoup.parse(myPage.asXml(), baseURI);
// clean up resources
webClient.close();
page.html中 - 源碼
<html>
<head>
<script src="loadData.js"></script>
</head>
<body onLoad="loadData()">
<div class="container">
<table id="data" border="1">
<tr>
<th>col1</th>
<th>col2</th>
</tr>
</table>
</div>
</body>
</html>
loadData.js
// append rows and cols to table.data in page.html
function loadData() {
data = document.getElementById("data");
for (var row = 0; row < 2; row++) {
var tr = document.createElement("tr");
for (var col = 0; col < 2; col++) {
td = document.createElement("td");
td.appendChild(document.createTextNode(row + "." + col));
tr.appendChild(td);
}
data.appendChild(tr);
}
}
page.html當加載到瀏覽器時
| Col1 | Col2 | | ------ | ------ | | 0.0 | 0.1 | | 1.0 | 1.1 |
使用jsoup解析的山坳數據
// load source from file
Document doc = Jsoup.parse(new File("page.html"), "UTF-8");
// iterate over row and col
for (Element row : doc.select("table#data > tbody > tr"))
for (Element col : row.select("td"))
// print results
System.out.println(col.ownText());
輸出
(空)
發生了什麼事page.html中?
Jsoup解析從服務器交付的源代碼(或者在這種情況下從文件加載)。它不會調用JavaScript或CSS DOM操作等客戶端操作。在這個例子中,行和列從不附加到數據表中。
如何解析我的頁面在瀏覽器中呈現?
// load page using HTML Unit and fire scripts
WebClient webClient = new WebClient();
HtmlPage myPage = webClient.getPage(new File("page.html").toURI().toURL());
// convert page to generated HTML and convert to document
doc = Jsoup.parse(myPage.asXml());
// iterate row and col
for (Element row : doc.select("table#data > tbody > tr"))
for (Element col : row.select("td"))
// print results
System.out.println(col.ownText());
// clean up resources
webClient.close();
輸出
0.0
0.1
1.0
1.1
你可以發佈你正在使用的生成'...'的代碼? – 2011-06-16 06:46:36
添加了代碼。此外,同樣的事情通過jSoup.connect(url).get() – sumit 2011-06-16 07:08:01
@submit展現出來:但是在這裏你已經構造了文檔。出現在哪裏? – 2011-06-16 07:23:32