0

大家好,我在 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);

所以有什么想法吗?

4

1 回答 1

1

顺便说一句,您的 HTML 看起来格式不正确,div之后您还有额外的first text:-

<div ...>first text<br><div><br></div>

其次,您可能需要使用matchesOwn,因为containsOwn将根据文档搜索特定文本。

尝试这个:-

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
于 2011-02-13T00:30:57.353 回答