简体   繁体   中英

Jsoup select a random one (1) from a class of div

In the page there are multiple divs of the same class like this one:

<div class="author-quote">
    <a href="#">Maldives</a>
</div>

Each div has an <a> tag and the text within the <a> tags are different.

now in my Java method:

private String get() throws InterruptedException{
        final CountDownLatch latch = new CountDownLatch(1);
        final List<String> value = new ArrayList<>();

        Thread thread = new Thread(new Runnable() {
            Elements elements;
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.connect(WEB_URL).get();

                    elements = doc.select("div.author-quote");
                    value.add(elements.text()); // added the whole class
                    latch.countDown();
                    } catch (IOException e) {
                    Log.e(TAG,e.getMessage());
                }
            }// end run
        });

        thread.start();
        latch.await();
        return value.get(0);
    }

And it gets all the texts from divs of the class author-quote . Here is the output:

Pakistan Maldives Lichtenstein China Panama

But I just want one of them, a random one. How do I do it?


ADDITIONAL INFORMATION : some <a> tags contain multi-word terms like Republic of Ireland and Guinea-Bissau and some have symbols like Dominican Rep.

Update : I am able to separate them using some string manipulations. But I hope I can do it with Jsoup's Element select tools.

you can split the value.get(0) by the delimiter " " (thus yielding an array of strings) then use a Random#nextInt to index into the array and pick a random String object.

...
...
...
String[] tempArray = value.get(0).split(" ");
return tempArray[new Random().nextInt(tempArray.length)];

UPDATE

As per your post update, another alternative solution would be from the web page side, you can surround all the divs that have a class attribute of author-quote within one main div element (if not already done) then select this parent div , thus enabling you to iterate over the parentDiv ChildNodes and collect their text individually then add to the ArrayList .

private String get() throws InterruptedException{
        final CountDownLatch latch = new CountDownLatch(1);
        final List<String> value = new ArrayList<>();

        Thread thread = new Thread(new Runnable() {
        Element parentDiv;
        @Override
        public void run() {
            try {
                Document doc = Jsoup.connect(WEB_URL).get();

                parentDiv = //getTheParentDivSomehow()
                for (Node child : parentDiv.childNodes()) {
                     Node tempNode = child.childNodes().get(0);
                     if (tempNode.childNodes().get(0) instanceof TextNode) 
                           value.add(((TextNode) child).text());

                }
                latch.countDown();
                } catch (IOException e) {
                Log.e(TAG,e.getMessage());
            }
        }// end run
        });

        thread.start();
        latch.await();
        Collections.shuffle(value);
        return value.get(new Random().nextInt(value.size()));
}
private String get() throws InterruptedException{
    final CountDownLatch latch = new CountDownLatch(1);
    final List<String> value = new ArrayList<>();

    Thread thread = new Thread(new Runnable() {
        Elements elements;
        @Override
        public void run() {
            try {
                Document doc = Jsoup.connect(WEB_URL).get();
                //returns a list of Elements
                elements = doc.select("div.author-quote"); 
                //use a random number and get the Element at that index to select one div element at random
                Random random = new Random();
                int randomIndex = random.nextInt(elements.size());//returns a random number between 0 and elements.size()
                value.add(elements.get(randomIndex).text()); // add only the text of the random Element
                latch.countDown();
                } catch (IOException e) {
                Log.e(TAG,e.getMessage());
            }
        }// end run
    });

    thread.start();
    latch.await();
    return value.get(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM