2016-05-29 94 views
0

我试图从网页中取消一些信息。我的问题是我得到的回报并不包含我要找的东西。从网页中刮去数据。 Java,HTMLUnit

如果我检查网页的源代码,我发现一个空的部分

<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()); 

回答

0

如果您在首次加载页面时检查页面的文本,则动态内容将不会被加载。 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> 
+0

你的想法奏效了。我用java实现它,调用页面并等待几秒钟,然后打印代码。 – ipop

0

您可以尝试jsoup

检查我想要数据的元素,它们出现在动态生成的部分内

该API允许使用最好的DOM,CSS和类似jquery的方法来提取和操作数据。也许你需要在数据加载AJAX之前执行一些操作。

+0

我试过Jsoup过,从我的理解是不支持javascript/AJAX,我猜是它用来填补空白。我'试图发送GET请求的数据,并似乎是在开始工作,仍然需要测试它更litle一点。 – ipop

+0

看起来像[无头浏览器](http://stackoverflow.com/questions/16852660/how-to-scrape-ajax-loaded-content-with-jsoup)的组合可能会诀窍。 – ekostadinov