문제

I want to extract data from one div class, but it is showing the whole string where I want to get data items one by one.

Document doc = Jsoup.parse(get_html);
String Title = doc.getElementsByClass("jTit").text();
String CoName = doc.getElementsByClass("coName").text();
System.out.println(Title);
System.out.println(CoName);
도움이 되었습니까?

해결책

You obviously have more than one element with the specified class, the getElementsByClass returns a collection containing all those Elements. So you probably want to extract the text of each one, for that you need to iterate over this collection the get each element and then get the text from it.

Here is an example

public class JsoupTest {
    @Test
    public void getTextByClass() {
        String html = "<html>\r\n" + 
                "    <body>\r\n" + 
                "        <div class=\"jTit\">jtit 1</div>\r\n" + 
                "        <div class=\"coName\">coname 1</div>\r\n" + 
                "        <div class=\"foo\">foo</div>\r\n" + 
                "        <div class=\"coName\">coname 2</div>\r\n" + 
                "        <div class=\"jTit\">jtit 2</div>\r\n" + 
                "        <div class=\"bar\">bar</div>\r\n" + 
                "    </body>\r\n" + 
                "</html>";

        Document doc = Jsoup.parse(html);

        Elements jTitElements = doc.getElementsByClass("jTit");
        for(Element e : jTitElements) {
            System.out.println(e.text());
        }

        Elements coNameElements = doc.getElementsByClass("coName");
        for(Element e : coNameElements) {
            System.out.println(e.text());
        }
    }
}

This prints:

jtit 1
jtit 2
coname 1
coname 2
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top