从网页中抓取数据。 Java, HTMLUnit

Scraping data from webpage. Java, HTMLUnit

我正在尝试从网页中抓取一些信息。我的问题是 return 我得到的不包含我要找的东西。

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

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

您可以尝试 jsoup for

inspect the elements I want data from, they appear inside that section generated dynamically

API 允许使用 DOM、CSS 和 jquery 类方法中的最佳方法来提取和操作数据。在数据 AJAX 加载之前,您可能需要执行一些操作。

如果您在首次加载页面时检查该页面的文本,则尚未加载动态内容。 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 
<section id="player-controller">

</section>
</body>
</html>