java - html解析器使用java搜索和替换一些值

标签 java jsoup html-parsing

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

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);
    }

}

最佳答案

此代码将文档中的相对链接更改为代码使用 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"));
        }
    }
}

关于java - html解析器使用java搜索和替换一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4844802/

相关文章:

java - 如何更新 map 中的值(如果存在)否则将其插入

html - Jsoup获取div内容

python - 将 BeautifulSoup 指向某个 <tr> 类

java - 尽管未使用复合键,但仍收到错误 "Foreign key must have same number of columns as the referenced primary key"

java - 仅在 Java 1.8.0_45 中出现 ConcurrentModificationException

java - 如何使用 Jsoup 选择具有空类的元素

java - 在 JSoup 中按类获取元素

java中的javascript解析器

javascript - 如何在不使用 XmlService 的情况下解析 Google Apps 脚本中的 HTML 字符串?

java - 不实际使用文件的 HTTP 文件上传