如何使用jsoup访问子类

时间:2016-04-19 03:52:16

标签: java web-crawler 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 = {...}

我使用的数据存储在脚本部分(最后一行)。我的想法是首先获取类“报告内容”,然后选择脚本。我的代码如下:

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

但仍然无法正常工作。我怎么能在这里获得脚本中的数据?感谢您的帮助!!!

2 个答案:

答案 0 :(得分:1)

请尝试使用此网址:

https://www.google.com/trends/trendsReport?hl=en&q=${keywords}&tz=${timezone}&content=1

,其中

  • ${keywords}是一个经过编码的空格分隔关键字列表
  • ${timezone}是Etc / GMT *格式的编码时区

DEMO

示例代码

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...

参考文献:

答案 1 :(得分:0)

尝试通过Id获得相同的内容,您将获得完整的标记