如何使用Jsoup从html文件中获取特定数据?

时间:2016-03-15 16:54:21

标签: java html web-crawler html-parsing jsoup

我正在使用当地语言新闻报道的html文件,我想收集新闻报道中仅使用当地语言的所有单词

我在html文件中观察到本地语言中的所有单词都在class field-content的div元素下,所以我选择了它的元素来获取数据,但div元素也包含像本地内部的元素语言词存在

<div class = "field-content"></div>

所以如何从html文件中只获取本地语言的单词

网站的网址:http://www.andhrabhoomi.net/

我的代码:

public static void main(String a[])
        {
            Document doc;
            try {
                 doc = Jsoup.connect("http://www.andhrabhoomi.net/").userAgent("Mozilla").get();
                 String title = doc.title();

                 System.out.println("title : " + title);

                    // get all links
                    //Elements links = doc.select("a[href]");

                    Elements body = doc.select("div.field-content");

                    for (Element link : body) {

                        System.out.println(link);


    // get the value from href attribute
                        //System.out.println("\nlink : " + link.attr("href"));
                        //System.out.println("text : " + link.text());
                    }

            }catch(IOException e){
                System.out.println("error\n");

            }
        }

2 个答案:

答案 0 :(得分:1)

不确定你在这之后是什么,但如果我猜对了,这应该会有所帮助。如果没有,请说出来,我们将从那里开始。

您希望通过获取field-content的任何类来更改您的选择,然后删除所有其他HTML内容,您需要将text()添加到结尾您的System.out.println( link.text() );见下文。

Elements body = doc.getElementsByClass( "field-content" );

for( Element link : body )
{
    System.out.println( link.text() );
}

答案 1 :(得分:0)

解决方案是:

        String title = doc.title();

        System.out.println("title : " + title);

        //get all links
        //Elements links = doc.select("a[href]");
        //Elements body = doc.select("div.field-content");
        Elements body = doc.select("div[class=\"field-content\"] > a");

        for (Element link : body) {

            System.out.println("---------------------------------------------------------------------------------------------------------------");
            System.out.println(link);

            Elements img = link.select("img");
            // get the value from href attribute
            System.out.print("\nSrc Img : " + img.attr("src"));

            Elements tag_a = link.select("a");
            System.out.println("\nHref : " + tag_a.attr("href"));
            //System.out.println("text : " + tag_a.text());
        }

    } catch (Exception e) {
        System.out.println("error\n");

    }
}