Jsoup在元素内部获取元素

时间:2018-08-06 22:13:31

标签: java jsoup

我正在尝试抓取以下页面:https://icobench.com/icos,并且在尝试使用ico_data类从元素中提取信息比特时遇到了麻烦。代码如下:

<td class="ico_data">
  <div class="image_box"><a href="/ico/gcox" class="image" style="background-image:url('/images/icos/icons/gcox.jpg');"></a></div>
  <div class="content">
    <a class="name" href="/ico/gcox"><object><a href="/premium" title="Premium" class="premium">&nbsp;</a></object>GCOX</a>
    <p>GCOX is the world's first blockchain-powered platform that allows the popularity of celebrities to be tokenised and listed.<br><br><b>Restrictions KYC:</b> Yes <span class="line">|</span> <b>Whitelist:</b> Yes <span class="line">|</span> <b>Countries:</b>      USA, Singapore</p>
  </div>
  <div class="shw">
    <div class="row"><b>Start:</b> 08 Aug 2018</div>
    <div class="row"><b>End:</b> 31 Aug 2018</div>
    <div class="row"><b>Rate:</b>
      <div class="rate color4">3.9</div>
    </div>
  </div>
</td>

我想提取名称,描述,开始日期,结束日期。我该怎么办?

到目前为止,这是我的代码:

Document document = Jsoup.connect("https://icobench.com/icos").userAgent("Mozilla").get();    
Elements companyElements = document.getElementsByClass("ico_data");
for (Element companyElement : companyElements) {
   // do stuff here
}

谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过过滤包含标签来过滤“开始”和“结束”。 在内容div中以“名称”类命名,并通过P标签进行描述。

public void extract(){
        try {
            Connection connection = Jsoup.connect("https://icobench.com/icos");
            Document document = connection.get();
            Elements companyElements = document.select(".ico_data");
            for (Element companyElement : companyElements) {

                if(companyElement.select(".content")!=null&&companyElement.select(".content").size()>0){

                    Element content = companyElement.select(".content").first();
                    String name = companyElement.select(".content").select(".name").text();
                    String description = companyElement.select(".content").select("p").text();
                    String start = companyElement.select("b:contains(Start)").first()
                            .parent().text().replace(companyElement.select("b:contains(Start)").first().text(),"");
                    String end = companyElement.select("b:contains(End)").first()
                            .parent().text().replace(companyElement.select("b:contains(End)").first().text(),"");

                }

                System.out.println(companyElement);
                // do stuff here
                }
        } catch (IOException e) {
            e.printStackTrace();
        }