我正在尝试读取 HTML 文件并添加指向某些文本的链接:
例如: 我想添加指向“Campaign0”文本的链接。 :
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">101</span></p></td>
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">Campaign0</span>
<td><p style="overflow: hidden; text-indent: 0px; "><span style="font-family: SansSerif;">unknown</span></p></td>
待添加链接:
<a href="Second.html">
我需要一个 JAVA 程序来修改 html 以在“Campaign0”上添加超链接。
我如何使用 Jsoup 做到这一点?
我用 JSoup 试过这个:
File input = new File("D://First.html");
Document doc = Jsoup.parse(input, "UTF-8", "");
Element span = doc.select("span").first(); <-- this is only for first span tag :(
span.wrap("<a href="Second.html"></a>");
这是正确的吗??它不工作:(
简而言之:有没有像-->
if find <span>Campaign0</span>
then replace by <span><a href="">Campaign0</a></span>
在 JAVA 代码中使用 JSoup 或任何技术??
最佳答案
您的代码看起来非常正确。要查找带有“Campaign0”、“Campaign1”等的跨度元素,您可以使用 JSoup 选择器“span:containsOwn(Campaign0)”。在 jsoup.org 中查看 JSoup 选择器的附加文档.
找到元素并用链接包装它们后,调用 doc.html() 应该返回修改后的 HTML 代码。这是一个工作示例:
输入.html:
<table>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign0</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
<tr>
<td><p><span>101</span></p></td>
<td><p><span>Campaign1</span></p></td>
<td><p><span>unknown</span></p></td>
</tr>
</table>
代码:
File input = new File("input.html");
Document doc = Jsoup.parse(input, "UTF-8", "");
Element span = doc.select("span:containsOwn(Campaign0)").first();
span.wrap("<a href=\"First.html\"></a>");
span = doc.select("span:containsOwn(Campaign1)").first();
span.wrap("<a href=\"Second.html\"></a>");
String html = doc.html();
BufferedWriter htmlWriter =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.html"), "UTF-8"));
htmlWriter.write(html);
htmlWriter.close();
输出:
<html>
<head></head>
<body>
<table>
<tbody>
<tr>
<td><p><span>101</span></p></td>
<td><p><a href="First.html"><span>Campaign0</span></a></p></td>
<td><p><span>unknown</span></p></td>
</tr>
<tr>
<td><p><span>101</span></p></td>
<td><p><a href="Second.html"><span>Campaign1</span></a></p></td>
<td><p><span>unknown</span></p></td>
</tr>
</tbody>
</table>
</body>
</html>
关于java - 使用 java 修改 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27860193/