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 に答える