【问题标题】:Jsoup find the nearest hrefJsoup 找到最近的href
【发布时间】:2014-04-28 22:45:20
【问题描述】:

我有一个字符串映射,基本上我现在正在做的是获取页面正文并使用jsoup.getPageBody().split("[^a-zA-Z]+") 将其拆分为单词,然后遍历页面正文并检查我的页面中是否存在任何单词字符串映射,如下所示:

for (String word : jsoup.getPageBody().split("[^a-zA-Z]+")) {
    if (wordIsInMap(word.toLowerCase()) {
        //At this part word is in string of maps
    }
}

当我在循环内部时,我想获得最近的超链接(href)。距离是由字数决定的。我在 jsoup 文档页面上找不到任何类似的示例。我该怎么做?

此页面的示例: http://en.wikipedia.org/wiki/2012_in_American_television

如果字符串的映射是racecrucial 那么我想得到:

http://en.wikipedia.org/wiki/Breeders%27_Cup_Classic

http://en.wikipedia.org/wiki/Fox_Broadcasting_Company

这两个链接。

【问题讨论】:

  • 您的字符串映射中的单词是什么?它们是html元素吗?它们是页面内容中的单词吗?
  • 是用户给的词
  • 如果你有一些示例 html,你可以展示它会让我们更容易想象我们正在谈论的内容
  • 我实际上使用维基百科页面。如en.wikipedia.org/wiki/2012_in_American_television
  • 所以您正试图捕获表格上最接近您给出的某个单词的链接?所以如果我给它“系统”这个词,它会返回“时代华纳有线电视”的链接。举个例子

标签: java html html-parsing jsoup href


【解决方案1】:

这是一个超级简单的实现,应该可以帮助您入门。但是,它不会根据字数找到最接近的链接。由您来修改。

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

import java.util.List;

public class Program {

public static void main(String...args) throws Exception {
    String searchFor = "online and";

    Document doc = Jsoup.connect("http://en.wikipedia.org/wiki/2012_in_American_television").get();
    Element element = doc.getElementsContainingOwnText(searchFor).first();

    Node nodeWithText = getFirstNodeContainingText(element.childNodes(), searchFor);
    Element closestLink = getClosestLink(nodeWithText);

    System.out.println("Link closest to '" + searchFor + "': " + closestLink.attr("abs:href"));
}

private static Element getClosestLink(Node node) {
    Element linkElem = null;
    if (node instanceof Element) {
        Element element = (Element) node;
        linkElem = element.getElementsByTag("a").first();
    }
    if (linkElem != null) {
        return linkElem;
    }

    // This node wasn't a link. try next one
    linkElem = getClosestLink(node.nextSibling());
    if (linkElem != null) {
        return linkElem;
    }

    // Wasn't next link. try previous
    linkElem = getClosestLink(node.previousSibling());
    if (linkElem != null) {
        return linkElem;
    }

    return null;
}

private static Node getFirstNodeContainingText(List<Node> nodes, String text) {
    for (Node node : nodes) {
        if (node instanceof TextNode) {
            String nodeText = ((TextNode) node).getWholeText();
            if (nodeText.contains(text)) {
                return node;
            }
        }
    }
    return null;
}

}

【讨论】:

  • 能解释一下getFirstNodeContainingText()方法的使用方法吗?
  • 该方法采用节点列表并从第一个节点开始简单地循环它们。它查看作为文本节点的节点(不是链接或 html 节点),如果节点的内容与该节点返回的文本匹配,则搜索完成。这样就可以找到包含文本的实际节点。
猜你喜欢
  • 2015-05-20
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
相关资源
最近更新 更多