我正在尝试阅读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以添加超链接&#34; Campaign0 &#34;
我是如何用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>");
这是对的吗?它不起作用:(
简而言之 :有什么类似的 - &gt;
if find <span>Campaign0</span>
then replace by <span><a href="">Campaign0</a></span>
使用JSoup或JAVA代码中的任何技术??
答案 0 :(得分:3)
您的代码似乎非常正确。要使用&#34; Campaign0&#34;,&#34; Campaign1&#34;等查找span元素,您可以使用JSoup选择器&#34; span:containsOwn(Campaign0)&#34;。请参阅jsoup.org上的JSoup选择器的其他文档。
找到元素并用链接包装后,调用doc.html()应该返回修改后的HTML代码。这是一个工作样本:
input.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>