[英]How to access the subclass using jsoup
我想訪問此網頁: https : //www.google.com/trends/explore#q=ice%20cream並提取中心線圖中的數據。 html文件是(在這里,我只粘貼我使用的部分。):
<div class="center-col">
<div class="comparison-summary-title-line">...</div>
...
<div id="reportContent" class="report-content">
<!-- This tag handles the report titles component -->
...
<div id="report">
<div id="reportMain">
<div class="timeSection">
<div class = "primaryBand timeBand">...</div>
...
<div aria-lable = "one-chart" style = "position: absolute; ...">
<svg ....>
...
<script type="text/javascript">
var chartData = {...}
我使用的數據存儲在腳本部分(最后一行)中。 我的想法是先獲取類“report-content”,然后選擇腳本。 我的代碼如下:
String html = "https://www.google.com/trends/explore#q=ice%20cream";
Document doc = Jsoup.connect(html).get();
Elements center = doc.getElementsByClass("center-col");
Element report = doc.getElementsByClass("report-content");
System.out.println(center);
System.out.println(report);
當我打印“center”類時,我可以得到除“report-content”之外的所有子類內容,當我打印“report-content”時,結果只有這樣:
<div id="reportContent" Class="report-content"></div>
我也試試這個:
Element report = doc.select(div.report-content).first();
但仍然根本不起作用。 我怎么能在這里獲取腳本中的數據? 我感謝您的幫助!!!
試試這個網址:
https://www.google.com/trends/trendsReport?hl=en&q=${keywords}&tz=${timezone}&content=1
在哪里
${keywords}
是一個編碼的空格分隔的關鍵字列表${timezone}
是 Etc/GMT* 形式的編碼時區String myKeywords = "ice cream";
String myTimezone = "Etc/GMT+2";
String url = "https://www.google.com/trends/trendsReport?hl=en&q=" + URLEncoder.encode(keywords, "UTF-8") +"&tz="+URLEncoder.encode(myTimezone, "UTF-8")+"&content=1";
Document doc = Jsoup.connect(url).timeout(10000).get();
Element scriptElement = doc.select("div#TIMESERIES_GRAPH_0-time-chart + script").first();
if (scriptElement==null) {
throw new RuntimeException("Unable to locate trends data.");
}
String jsCode = scriptElement.html();
// parse jsCode to extract charData...
參考:
嘗試通過 Id 獲得相同的結果,您將獲得完整的標簽
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.