我正在尝试抓取出价网站的内容,但无法获取该网站的完整页面。我在xulrunner上使用crowbar首先获取页面(因为ajax以懒惰方式加载某些元素)然后从文件中删除。 但是在bidrivals网站的主页上,即使本地文件格式正确,也会失败。 jSoup似乎只是在html代码中途以'...'字符结束。 如果有人以前遇到过此,请帮忙。 [this link]要求使用以下代码。
File f = new File(projectLocation+logFile+"bidrivalsHome");
try {
f.createNewFile();
log.warn("Trying to fetch mainpage through a console.");
WinRedirect.redirect(projectLocation+"Curl.exe -s --data \"url="+website+"&delay="+timeDelay+"\" http://127.0.0.1:10000", projectLocation, logFile+"bidrivalsHome");
} catch (Exception e) {
e.printStackTrace();
log.warn("Error in fetching the nameList", e);
}
Document doc = new Document("");
try {
doc = Jsoup.parse(f, "UTF-8", website);
} catch (IOException e1) {
System.out.println("Error while parsing the document.");
e1.printStackTrace();
log.warn("Error in parsing homepage", e1);
}
答案 0 :(得分:1)
尝试使用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解析page.html的col数据
// 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());
<强>输出强>
(空)
发生了什么事?
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