【问题标题】:Find content of href link and URL in Java在 Java 中查找 href 链接和 URL 的内容
【发布时间】:2012-05-05 05:56:47
【问题描述】:

我想解析这个链接:

<a href="http://www.google.fr">Link to google</a>

为了得到两个结果:

Link = "http://www.google.fr"
LinkName = "Link to google"

我真的不知道该怎么做,Java中有解决这个问题的库吗?

提前致谢,

【问题讨论】:

标签: java href


【解决方案1】:

使用jsoup解析器:

示例:

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
    String linkHref = link.attr("href");
  String linkText = link.text();
}

【讨论】:

    【解决方案2】:

    这样就可以了。

    public class Parse
    {
      public static void main(String[] args)
      {
        String h = " <a href=\"http://www.google.fr\">Link to google</a>";
        int n = getIndexOf(h, '"', 0);
    
        String[] a = h.substring(n).split(">");
        String url = a[0].replaceAll("\"", "");
        String value = a[1].replaceAll("</a", "");
    
        System.out.println(url + " - " + value);
      }
    
      public static int getIndexOf(String str, char c, int n)
      {
        int pos = str.indexOf(c, 0);
        while (n-- > 0 && pos != -1)
        {
          pos = str.indexOf(c, pos + 1);
        }
        return pos;
      }
    }
    

    【讨论】:

    • 这是不好的做法。您应该避免依赖于角色定位。请参阅 Nurlan 的回答。
    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2021-12-14
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2021-11-19
    相关资源
    最近更新 更多