【问题标题】:How to access the subclass using jsoup如何使用 jsoup 访问子类
【发布时间】:2016-04-19 03:52:16
【问题描述】:

我想访问这个网页: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);

当我打印“中心”类时,我可以获得除“报告内容”之外的所有子类内容,而当我打印“报告内容”时,结果只是:

      <div id="reportContent" Class="report-content"></div>

我也试试这个:

  Element report = doc.select(div.report-content).first();

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

【问题讨论】:

标签: java web-crawler jsoup


【解决方案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...

参考资料:

【讨论】:

  • 非常感谢!太棒了~~!
【解决方案2】:

尝试通过 Id 获取相同的,你会得到完整的标签

【讨论】:

  • 谢谢!当我使用作为 id 的“doc.select(div.reportContent)”时,结果为空。当我使用类“doc.select(div.report-content)”时,结果是
    没有内容。然后我也无法在此类中获取脚本。
  • 你试过getElementById("reportMain")吗?
  • 猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多