![](/img/trans.png)
[英]How to get just first element in html fie By using jsoup in JAVA
[英]How to get element by tags using JSoup? - java
如何使用JSoup( http://jsoup.org/ )通過標簽獲取元素?
我有以下輸入,並需要以下輸出,但我沒有在<source>...<\\source>
標記內獲取文本:
[在:]
<html>
<something>
<source>foo bar bar</source>
<something>
<source>foo foo bar</source>
</html>
[要求:]
foo bar bar
foo foo bar
我已經試過了:
import java.io.*;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class HelloJsoup {
public static void main(String[] args) throws IOException {
String br = "<html><source>foo bar bar</source></html>";
Document doc = Jsoup.parse(br);
//System.out.println(doc);
for (Element sentence : doc.getElementsByTag("source"))
System.out.print(sentence);
}
}
但它輸出:
<source></source>
您需要使用xmlParser()
,您可以將其傳遞給parse()
方法:
String br = "<html><source>foo bar bar</source></html>";
Document doc = Jsoup.parse(br, "", Parser.xmlParser());
for (Element sentence : doc.getElementsByTag("source"))
System.out.println(sentence.text());
}
在文檔中對此有更多了解: http : //jsoup.org/apidocs/org/jsoup/parser/Parser.html#xmlParser()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.