【发布时间】: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