[英]Jsoup select a random one (1) from a class of div
在頁面中,同一個類有多個div,如下所示:
<div class="author-quote">
<a href="#">Maldives</a>
</div>
每個div有一個<a>
標簽和內文<a>
標簽是不同的。
現在在我的Java方法中:
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);
}
它從author-quote
類的div中獲取所有文本。 這是輸出:
Pakistan Maldives Lichtenstein China Panama
但是我只想要其中一個,一個隨機的。 我該怎么做?
其他信息 :某些<a>
標記包含多詞術語,例如愛爾蘭共和國和幾內亞比紹,而有些則具有符號,例如多米尼加共和國。
更新 :我能夠使用一些字符串操作將它們分開。 但是我希望我可以使用Jsoup的Element選擇工具來做到這一點。
您可以用定界符" "
分割value.get(0)
(從而產生一個字符串數組),然后使用Random#nextInt
將該數組索引並選擇一個隨機String
對象。
...
...
...
String[] tempArray = value.get(0).split(" ");
return tempArray[new Random().nextInt(tempArray.length)];
UPDATE
根據您的帖子更新,另一種替代解決方案將從網頁一側開始,您可以將所有具有author-quote
class
屬性的div包圍在一個主div
元素中(如果尚未完成),然后選擇此父div
,使您可以遍歷parentDiv
節點並分別收集其文本,然后添加到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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.