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

How to get specific data from a html file using Jsoup?

我有一份本地语言报纸的 html 文件,我想收集报纸中所有仅使用本地语言的单词

我在 html 文件中观察到所有本地语言的单词都在 class 字段内容的 div 元素下,所以我选择了它的元素来获取数据,但 div 元素还包含诸如其中存在本地语言单词的元素

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

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

url 的站点: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");

            }
        }

不确定你在找什么,但如果我的猜测是正确的,这应该有所帮助。如果没有,就说出来,我们从那里开始。

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

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

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

解决方法是:

        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");

    }
}