【问题标题】:How to replace links in existing html document with new links?如何用新链接替换现有 html 文档中的链接?
【发布时间】:2018-10-13 00:01:21
【问题描述】:

我有一个包含多个链接的 HTML 文档,我需要将此 HTML 文档中的链接更改为新链接。 示例:输入 html 文档: https://stackoverflow.com">stackoverflow https://stackoverflow1.com">stackoverflow1

输出html文档: 堆栈溢出 堆栈溢出1

我正在使用 jsoup 解析器从我的文档中获取所有链接的列表。 我在替换 html 文件中的链接时遇到了困难。

以下是我的代码 sn-p:运行代码后,我的 test.html 没有更新为新链接。

Path path = Paths.get("test.html");
    Charset charset = StandardCharsets.UTF_8;
    Document doc;
    try {
        doc = Jsoup.parse(new File("test.html"), "UTF-8");
        Element content = doc.getElementById("ExtractLinks");
        Elements links = content.getElementsByTag("a");

        for (Element link : links) {
            String linkHref = link.attr("href");
            System.out.println("URL:" + linkHref);
            String fileContent = new String(Files.readAllBytes(path), charset);
            fileContent = fileContent.replaceAll(linkHref, "www.google.com");
            Files.write(path, fileContent.getBytes(charset));
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

【问题讨论】:

  • 你把你的链接放在哪里?它在锚标签内吗?
  • 是的,链接在锚标签内

标签: java html file parsing jsoup


【解决方案1】:

这是你的意思吗?你只需要JS。

var anchor_tags = document.getElementsByTagName("a");
    for (var i = 0; i < anchor_tags.length; i++) {
        var orig_href = anchor_tags[i].href;
        var new_href = orig_href.replace("https://","");
        var final_href = new_href.replace(".com/","");
        alert(final_href);
    }
<a href="https://stackoverflow.com"></a>
    <a href="https://stackoverflow1.com"></a>

【讨论】:

  • 我不想要 javascript 中的代码 :( 我需要 java 中的代码
猜你喜欢
  • 1970-01-01
  • 2018-03-30
  • 2014-08-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 2019-10-20
  • 2014-05-19
  • 1970-01-01
相关资源
最近更新 更多