我正试着从网页上搜集一些信息。我的问题是我得到的回报不包含我想要的东西。
如果我检查web的源代码,就会发现一个空部分。
<section id="player-controller">
</section>但是,如果我检查我想要数据的元素,它们就会出现在该部分中。
由于它是动态生成的,所以我尝试使用HTMLUnit,但仍然无法得到它。也许我看错了。
有什么方法可以用HTMLUnit获取代码,还是应该使用不同的工具?
解决了
通过使用HTMLUnit并在打印页面之前让进程停止一段时间,我得到了打印缺少的内容
WebClient webclient = new WebClient();
HtmlPage currentPage = webclient.getPage("https://www.dubtrack.fm/join/chilloutroom");
Thread.sleep(2000);
System.out.println(currentPage.asXml());发布于 2016-05-29 19:50:57
如果您在第一次加载页面时检查它的文本,则动态内容还不会被加载。callScraper.html中的javascript将调用另一个页面,然后在读取HTML元素的内容之前等待两秒钟。在这里,时机可能很棘手。我希望下面的代码会有所帮助。
callScraper.html
<!DOCTYPE html>
<head>
<title>Call test for scraping</title
<meta charset="UTF-8" />
<script>
var newWindow;
var contents;
function timed() {
contents.value = contents.value + "\r\n" +"function timed started" + "\r\n";
contents.value = contents.value + "\r\n" + newWindow.document.getElementById("player-controller").innerHTML;
}
function starter() {
// alert("Running starter");
contents = document.getElementById("contents");
newWindow = window.open("scraper.html");
contents.value = contents.value + "\r\nTimer started\r\n";
setTimeout(timed, 2000);
}
window.onload=starter;
</script>
</head>
<body>
<p>This will open another page and then diplay an element from that page.</p>
<form name="reveal">
<textarea id="contents" cols="50" rows="50"></textarea>
</form>
</body>
</html>scraper.html
<!DOCTYPE html>
<head>
<title>Test for scraping</title>
<meta charset="UTF-8" />
<script>
var section;
function starter() {
section = document.getElementById("player-controller");
// alert(":"+section.innerHTML+";");
section.innerHTML = "<p>inner text</p>";
// alert(":" +section.innerHTML + ":");
}
window.onload = starter;
</script>
</head>
<body>
<p>See http://stackoverflow.com/questions/37513393/scrapping-data-from-webpage-java-htmlunit</p>
<section id="player-controller">
</section>
</body>
</html>发布于 2016-05-29 18:29:34
https://stackoverflow.com/questions/37513393
复制相似问题