如何使用jsoup在某些标签之后提取文本

时间:2013-12-06 20:13:47

标签: java twitter jsoup

我正在使用jsoup来提取高音文本。所以html结构是

 <p class="js-tweet-text tweet-text">@sexyazzjas There is so much love in the air, Jasmine! Thanks for the shout out. <a href="/search?q=%23ATTLove&amp;src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr" ><s>#</s><b>ATTLove</b></a></p>

我想得到的是There is so much love in the air, Jasmine! Thanks for the shout out. 我想提取整个页面中的所有高音单元文本。 我是java的新手。代码有bug。请帮帮我谢谢

下面是我的代码:

    package htmlparser;
    import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class tweettxt {

    public static void main(String[] args) {

        Document doc;
        try {

            // need http protocol
            doc = Jsoup.connect("https://twitter.com/ATT/").get();

            // get page title
            String title = doc.title();
            System.out.println("title : " + title);

            Elements links = doc.select("p class="js-tweet-text tweet-text"");
            for (Element link : links) {


                System.out.println("\nlink : " + link.attr("p"));
                System.out.println("text : " + link.text());

            }






        } catch (IOException e) {
            e.printStackTrace();
        }

      }

    }

1 个答案:

答案 0 :(得分:2)

虽然我同意Robin Green关于在这种情况下使用API​​而不是Jsoup的意见,但我将提供一个有效的解决方案,用于关闭此主题的内容,并为将来遇到问题的观众提供帮助

  1. 带有两个或多个类的标记的选择器
  2. 获取包含其他元素的Jsoup元素的直接文本。

    public static void main(String[] args) {
    
        Document doc;
        try {
    
            // need http protocol
            doc = Jsoup.connect("https://twitter.com/ATT/").get();
    
            // get page title
            String title = doc.title();
            System.out.println("title : " + title);
    
            //select this <p class="js-tweet-text tweet-text"></p>
            Elements links = doc.select("p.js-tweet-text.tweet-text");  
    
            for (Element link : links) {
                System.out.println("\nlink : " + link.attr("p"));
                 /*use ownText() instead of text() in order to grab the direct text of 
                 <p> and not the text that belongs to <p>'s children*/
                System.out.println("text : " + link.ownText());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }