我有Element
:
<td id="color" align="center">
Z 29.02-23.05 someText,
<br>
some.Text2 <a href="man.php?id=111">J. Smith</a> (l.)
</td>
如何在标记<br>
之后获取文字,看起来像some.Text2 J. Smith
我试图在文档中找到答案,但是......
如果我使用
System.out.println(element.select("a").text());
我只得到 J。史密斯。。不幸的是,我不知道如何解析像<br>
答案 0 :(得分:3)
Node.childNodes
可以挽救你的生命:
package com.github.davidepastore.stackoverflow35436825;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
/**
* Stackoverflow 35436825
*
*/
public class App
{
public static void main( String[] args )
{
String html = "<html><body><table><tr><td id=\"color\" align=\"center\">" +
"Z 29.02-23.05 someText," +
"<br>" +
"some.Text2 <a href=\"man.php?id=111\">J. Smith</a> (l.) " +
"</td></tr></table></body></html>";
Document doc = Jsoup.parse( html );
Element td = doc.getElementById( "color" );
String text = getText( td );
System.out.println("Text: " + text);
}
/**
* Get the custom text from the given {@link Element}.
* @param element The {@link Element} from which get the custom text.
* @return Returns the custom text.
*/
private static String getText(Element element) {
String working = "";
List<Node> childNodes = element.childNodes();
boolean brFound = false;
for (int i = 0; i < childNodes.size(); i++) {
Node child = childNodes.get( i );
if (child instanceof TextNode) {
if(brFound){
working += ((TextNode) child).text();
}
}
if (child instanceof Element) {
Element childElement = (Element)child;
if(brFound){
working += childElement.text();
}
if(childElement.tagName().equals( "br" )){
brFound = true;
}
}
}
return working;
}
}
输出将是:
Text: some.Text2 J. Smith (l.)
答案 1 :(得分:1)
据我所知,您只能在两个标签之间接收文字,这在您的文档中只有一个<br/>
标签是不可能的。
我能想到的唯一选择是使用split()
来接收第二部分:
String partAfterBr = element.text().split("<br>")[1];
Document relevantPart = JSoup.parse(partAfterBr);
// do whatever you want with the Document in order to receive the necessary parts