从Div标签获取文本 [英] Getting text from Div tags

查看:384
本文介绍了从Div标签获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个div标签的主Div标签,如下所示.子Div标签没有与其他子div标签区别的类/标识.现在,我想从第二个子Div标签中提取文本值.我该怎么办?

I have a main Div tag with multiple div tags as below. The child Div tags have no class/id that distinguishes from the other child div tags. Now I want to extract the text value from the 2nd child Div tag. How can i do that?

<div class="logFor" style="position: relative; height: 101px; padding: 5px;">
     <div style="color: #6b6b6b; font-weight: bold;">This is a monster</div>
     <div style="overflow: hidden; height: 28px; margin-top: 3px; color: #1b1f2e;">Monster in Black</div>
     <div style="position: absolute; left: 5px; bottom: 0;">
     <div style="position: absolute; right: 5px; bottom: 0;">
</div>

我想获得文本黑色怪物".该Div没有ID/名称,并且不确定此样式是否相同或更改.我将如何使用jSoup提取内容?

I want to get the text "Monster in Black". This Div doesnt have an id/name and not sure if this style would be same or change. How would i extract using jSoup?

推荐答案

package stackoverflow;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JSoupTest {
    public static void main(String[] args) throws IOException {
        InputStream in = JSoupTest.class.getResourceAsStream("JSoupTest.txt");

        String html = IOUtils.toString(in);

        Document doc = Jsoup.parse(html);

        Elements divs = doc.select("DIV");
        System.out.println(divs);

        Element div = divs.get(2);
        System.out.println("Monster in Black".equals(div.text()));
    }
}

产生:

<div class="logFor" style="position: relative; height: 101px; padding: 5px;"> 
 <div style="color: #6b6b6b; font-weight: bold;">
  This is a monster
 </div> 
 <div style="overflow: hidden; height: 28px; margin-top: 3px; color: #1b1f2e;">
  Monster in Black
 </div> 
 <div style="position: absolute; left: 5px; bottom: 0;"> 
  <div style="position: absolute; right: 5px; bottom: 0;"> 
  </div> 
 </div>
</div>
<div style="color: #6b6b6b; font-weight: bold;">
 This is a monster
</div>
<div style="overflow: hidden; height: 28px; margin-top: 3px; color: #1b1f2e;">
 Monster in Black
</div>
<div style="position: absolute; left: 5px; bottom: 0;"> 
 <div style="position: absolute; right: 5px; bottom: 0;"> 
 </div> 
</div>
<div style="position: absolute; right: 5px; bottom: 0;"> 
</div>
true

这篇关于从Div标签获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆