大家好 我在java-ee应用程序中使用jsoup来解析html
我想获得包含文字的第一个标签, 当我试图运行以下代码时,我得到了一个例外:
org.jsoup.select.Selector$SelectorParseException: Could not parse query :containsOwn(text)
at org.jsoup.select.Selector.findElements(Selector.java:143)
at org.jsoup.select.Selector.select(Selector.java:90)
at org.jsoup.select.Selector.select(Selector.java:68)
at org.jsoup.nodes.Element.select(Element.java:162)
代码是:
String html = "<html><head><style type=\"text/css\"></style></head><body><div style=\"font-family:times new roman,new york,times,serif;font-size:14pt\">first text<br><div><br></div><div style=\"font-family: times new roman,new york,times,serif; font-size: 14pt;\"><br><div style=\"font-family: times new roman,new york,times,serif; font-size: 12pt;\"><font size=\"2\" face=\"Tahoma\"><hr size=\"1\"><b><span style=\"font-weight: bold;\">one:</span></b> second text<br><b><span style=\"font-weight: bold;\">two:</span></b> third text<br><b><span style=\"font-weight: bold;\">three:</span></b> fourth text<br><b><span style=\"font-weight: bold;\">five:</span></b> fifth text<br></font><br>";
Document document = Jsoup.parse(html);
String firstText = document.select(":containsOwn(text)").first().text();
System.out.println(firstText);
所以有什么想法吗?
答案 0 :(得分:1)
顺便说一句,您的HTML看起来不太好,div
之后还有额外的first text
: -
<div ...>first text<br><div><br></div>
其次,您可能需要使用matchesOwn
,因为containsOwn
会根据documentation搜索特定文字。
试试这个: -
String html = "<html><head><style type=\"text/css\"></style></head><body><div style=\"font-family:times new roman,new york,times,serif;font-size:14pt\">first text<br><br></div><div style=\"font-family: times new roman,new york,times,serif; font-size: 14pt;\"><br><div style=\"font-family: times new roman,new york,times,serif; font-size: 12pt;\"><font size=\"2\" face=\"Tahoma\"><hr size=\"1\"><b><span style=\"font-weight: bold;\">one:</span></b> second text<br><b><span style=\"font-weight: bold;\">two:</span></b> third text<br><b><span style=\"font-weight: bold;\">three:</span></b> fourth text<br><b><span style=\"font-weight: bold;\">five:</span></b> fifth text<br></font><br>";
Document document = Jsoup.parse(html);
String firstText = document.select("div:matchesOwn(\\w+)").first().text();
System.out.println(firstText);
...并且打印结果是: -
first text