2

我正在寻找一个可以搜索和替换锚标记的 html 解析器,例如

ex
<a href="/ima/index.php">example</a>
to
<a href="http://www.example.com/ima/index.php">example</a>

更新:

我的代码与 jsoup 但不工作

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.collect.ImmutableList;
import com.google.common.net.InternetDomainName;

public class test {
    public static void main(String args[]) throws IOException {

          Document doc = Jsoup.connect("http://www.google.com").get();

          String html =doc.outerHtml().toString();

         // System.out.println(html);

           Elements links = doc.select("a");



            for (Element link : links) {
             String href=link.attr("href");
             if(href.startsWith("http://"))
             {

             }
             else
             {
                 html.replaceAll(href,"http://www.google.com"+href);
             }
            }
            System.out.println(html);
    }

}
4

4 回答 4

5

此代码将文档中的相对链接更改为绝对链接代码使用 jsoup 库

private void absoluteLinks(Document document, String baseUri)    {
    Elements links = document.select("a[href]");
    for (Element link : links)  {
        if (!link.attr("href").toLowerCase().startsWith("http://"))    {
            link.attr("href", baseUri+link.attr("href"));
        }
    }
}
于 2012-11-19T16:34:57.513 回答
2
package javaapplication4;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author derek
 */
public class Main
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        try
        {
            Document document = Jsoup.connect("http://www.google.com").get();
            Elements elements = document.select("a");

            for (Element element : elements)
            {
                element.baseUri();
            }
            System.out.println(document);
        }
        catch (Exception e)
        {
            e.printStackTrace(System.err);
        }
    }
}
于 2011-03-14T16:03:34.877 回答
1

您可以使用 String.replaceAll() 和匹配的正则表达式来做到这一点

<a href="/

查找所有相关链接。

html = html.replaceAll("<a href=\"/", "<a href=\"http://www.google.com/\"");
于 2011-01-30T19:04:41.783 回答
0

这是一个编程问题吗?如果您正在寻找一个预制的 Java 文件或其他类似的东西,那么您来错地方了。如果你想写这样的东西,那么你可以只搜索以 开头a href=/"和结尾的文本实例/">,然后你可以检查 href 值,以及它是否是相对路径(即以 开头/) ,您可以将其他文本添加到开头。

于 2011-01-30T19:04:46.293 回答