首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使用java搜索和替换某些值的html解析器

使用java搜索和替换某些值的html解析器
EN

Stack Overflow用户
提问于 2011-01-30 18:55:55
回答 4查看 8.2K关注 0票数 2

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

代码语言:javascript
运行
AI代码解释
复制
ex
<a href="/ima/index.php">example</a>
to
<a href="http://www.example.com/ima/index.php">example</a>

更新:

我的代码使用了jsoup,但无法正常工作

代码语言:javascript
运行
AI代码解释
复制
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);
    }

}
EN

回答 4

Stack Overflow用户

发布于 2012-11-19 16:34:58

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

代码语言:javascript
运行
AI代码解释
复制
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"));
        }
    }
}
票数 5
EN

Stack Overflow用户

发布于 2011-03-14 16:03:35

代码语言:javascript
运行
AI代码解释
复制
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);
        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2011-01-30 19:04:42

您可以使用String.replaceAll()和一个匹配

代码语言:javascript
运行
AI代码解释
复制
<a href="/

要查找所有相对链接,请执行以下操作。

代码语言:javascript
运行
AI代码解释
复制
html = html.replaceAll("<a href=\"/", "<a href=\"http://www.google.com/\"");
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4844802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档