加载此页面时,我对HtmlPage对象中返回的动态内容没有任何运气:https://www.fangraphs.com/leaders/splits-leaderboards?splitArr=5&strgroup=season&statgroup=1&startDate=2018-03-01&endDate=2018-11-01&filter=IP%7Cgt%7C0&position=P&statType=player&autoPt=true&players=&pg=0&pageItems=30&sort=22,1&splitArrPitch=&splitTeams=false
“ react-drop-test” div为空。我试图找到带有“导出数据”文本的锚点,以便可以单击它并以流的形式获取内容。
关于如何使HtmlPage包含动态内容的任何想法?
这里是我现在拥有的示例。锚永远不会返回任何元素。
webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getCookieManager().setCookiesEnabled(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.setJavaScriptTimeout(jsTimeout);
updateJSErrorListener(webClient);
int thisYear = year;
if (isEarlySeason()) {
thisYear = year - 1;
}
String leftyURL = "https://www.fangraphs.com/leaderssplits.aspx?splitArr=5&strgroup=season&statgroup=1&startDate=" + thisYear + "-03-01&endDate=" + year + "-11-01&filter=IP%7Cgt%7C0&position=P&statType=player&autoPt=true&players=&pg=0&pageItems=30&sort=22,1";
HtmlPage page = webClient.getPage(leftyURL);
HtmlAnchor leftyAnchor = null;
HtmlDivision div = (HtmlDivision) page.getElementById("react-drop-test");
List<HtmlElement> anchors = div.getElementsByTagName("a");
for (DomElement anchor:anchors2) {
if ((anchor.getAttribute("class").contains("data-export"))) {
leftyAnchor = (HtmlAnchor) anchor;
break;
}
}
Page p = leftyAnchor.click();
InputStream is = p.getWebResponse().getContentAsStream();
List<List<String>> leftyCSV = readCSVFile(is);
答案 0 :(得分:0)
另一个充满奇怪js的网页。因此,让我从一些一般性提示开始:
最后:您需要HtmlUnit的更新版本才能完成工作,因为javascript impl misses one feature可以使此页面正常工作所使用的javascript代码。
要获取新的(SNAPSHOT)版本,您可以使用以下选项:
使用最新的代码库,它将为您完成这项工作:
String url = "https://www.fangraphs.com/leaders/splits-leaderboards?splitArr=5&strgroup=season&statgroup=1&startDate=2018-03-01&endDate=2018-11-01&filter=IP%7Cgt%7C0&position=P&statType=player&autoPt=true&players=&pg=0&pageItems=30&sort=22,1&splitArrPitch=&splitTeams=false";
try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_60)) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage page = webClient.getPage(url);
webClient.waitForBackgroundJavaScript(50000);
System.out.println("----------------");
System.out.println(page.asText());
HtmlDivision div = (HtmlDivision) page.getElementById("react-drop-test");
List<HtmlElement> anchors = div.getElementsByTagName("a");
for (DomElement anchor:anchors) {
if ((anchor.getAttribute("class").contains("data-export"))) {
HtmlAnchor leftyAnchor = (HtmlAnchor) anchor;
Page p = leftyAnchor.click();
System.out.println();
System.out.println("----------------");
System.out.println(p.getWebResponse().getContentAsString());
break;
}
}
}