【问题标题】:Get the second word from the div using JSoup使用 JSoup 从 div 中获取第二个单词
【发布时间】:2017-08-03 01:23:25
【问题描述】:

我的代码我得到了 div 中的所有单词。我需要做什么才能只获取 div 内的第二个单词?

例如:

<div id="div01"> FIRSTWORD SECONDWORD </DIV>

我的代码:

Document doc = Jsoup.connect(url).get();

Elements statistics = doc.select(div.div01);

textDiv1 = statistics.text();

【问题讨论】:

    标签: javascript android android-studio jsoup screen-scraping


    【解决方案1】:

    为什么不像在 Java 字符串中获取第二个单词那样做呢?

    String secondWord = line.split(" ")[1]; //add your own checks to avoid out of bounds or null exceptions.
    

    扩展已有内容的示例:

    if (textDiv1 != null) {
        String[] words = textDiv1.split(" ");   //split our text into individual words, which are separated by spaces
        if (words.length >= 2) {                //there are at least two words
            String secondWord = words[1];
        }
        //otherwise, there is no second word, so you can handle it here
    }
    //there is no text found as textDiv1 is null
    

    ** 除非您的第二个单词恰好在它自己的元素中,否则 JSOUP 不会区分这点 **

    【讨论】:

    • mmm...如何在我的代码中应用它?... sry.. 我是新手
    • "line.split" 和 "words.size" 在 android studio 中出错
    • @ThyagoS size 对我来说是一个愚蠢的错误(这是 Kotlin 的)。应该是长度。 split 不应该是一个错误,我在我的 ide 上测试了它。确保你事先写好了你的东西,并且 textDiv1 已经被定义为一个字符串
    • 我放 line.split... 的任何地方都不起作用...“拆分”变红
    • @ThyagoS 你能在你的问题中发布你到目前为止的所有内容吗?当你将鼠标悬停在 split 上时它会说什么?
    【解决方案2】:

    @AllanW 最后一个代码是示例代码。它是我真正的代码:

    private class Div1 extends AsyncTask<String, String, String> {
            String text = null;
            String text2 = null;
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
    
            }
    
            @Override
            protected String doInBackground(String... params) {
    
                try {
                    // Connect to the web site
                    Document doc = Jsoup.connect(url).get();
    
                    // Using Elements to get the Meta data
                    Elements statistics = doc.select("div.statistics__userInfo > div");
    
                    if (text !=null){
    
                        String[] words = text.split("");
                        if (words.length >= 2) {
                            String secondWord = words[1];
                        }
                    }
                    Elements span1 = doc.getElementsByTag("span");
                    doc.getElementsByTag("span").remove();
                    // Locate the content attribute
                    text = statistics.text();
                    text2 = span1.text();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return text;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2017-01-30
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多