如何使用 java 和 jsoup 解析 HTML 文本和链接
How to parse HTML text and links with java and jsoup
我需要解析网页中的文本。正文是这样呈现的:
nonClickableText= link1 link2 nonClickableText2= link1 link2
我希望能够在 java 中将所有内容转换为字符串。不可点击的文本应保持原样,而可点击的文本应替换为实际的 link.
所以在 java 我会这样:
String parsedHTML = "nonClickableText= example.com example.com nonClickableText2= example3.com example4.com";
link1
和 link2
到底是什么?根据你的例子
"... nonClickableText2= example3.com example4.com"
它们可能不同,那么除了 href
之外还有什么来源?
根据您的图像,以下代码应该为您提供采用最终字符串演示文稿的所有内容。首先我们抓取 <strong>
-block 然后遍历子节点,使用 <a>
-children 和前面的文本节点:
String htmlString = "<html><div><p><strong>\"notClickable1\"<a rel=\"nofollow\" target=\"_blank\" href=\"example1.com\">clickable</a>\"notClickable2\"<a rel=\"nofollow\" target=\"_blank\" href=\"example2.com\">clickable</a>\"notClickable3\"<a rel=\"nofollow\" target=\"_blank\" href=\"example3.com\">clickable</a></strong></p></div></html>";
Document doc = Jsoup.parse(htmlString); //can be replaced with Jsoup.connect("yourUrl").get();
String parsedHTML = "";
Element container = doc.select("div>p>strong").first();
for (Node node : container.childNodes()) {
if(node.nodeName().equals("a") && node.previousSibling().nodeName().equals("#text")){
parsedHTML += node.previousSibling().toString().replaceAll("\"", "");
parsedHTML += "= " + node.attr("href").toString() + " ";
}
}
parsedHTML.trim();
System.out.println(parsedHTML);
输出:
notClickable1= example1.com notClickable2= example2.com notClickable3= example3.com
我需要解析网页中的文本。正文是这样呈现的:
nonClickableText= link1 link2 nonClickableText2= link1 link2
我希望能够在 java 中将所有内容转换为字符串。不可点击的文本应保持原样,而可点击的文本应替换为实际的 link.
所以在 java 我会这样:
String parsedHTML = "nonClickableText= example.com example.com nonClickableText2= example3.com example4.com";
link1
和 link2
到底是什么?根据你的例子
"... nonClickableText2= example3.com example4.com"
它们可能不同,那么除了 href
之外还有什么来源?
根据您的图像,以下代码应该为您提供采用最终字符串演示文稿的所有内容。首先我们抓取 <strong>
-block 然后遍历子节点,使用 <a>
-children 和前面的文本节点:
String htmlString = "<html><div><p><strong>\"notClickable1\"<a rel=\"nofollow\" target=\"_blank\" href=\"example1.com\">clickable</a>\"notClickable2\"<a rel=\"nofollow\" target=\"_blank\" href=\"example2.com\">clickable</a>\"notClickable3\"<a rel=\"nofollow\" target=\"_blank\" href=\"example3.com\">clickable</a></strong></p></div></html>";
Document doc = Jsoup.parse(htmlString); //can be replaced with Jsoup.connect("yourUrl").get();
String parsedHTML = "";
Element container = doc.select("div>p>strong").first();
for (Node node : container.childNodes()) {
if(node.nodeName().equals("a") && node.previousSibling().nodeName().equals("#text")){
parsedHTML += node.previousSibling().toString().replaceAll("\"", "");
parsedHTML += "= " + node.attr("href").toString() + " ";
}
}
parsedHTML.trim();
System.out.println(parsedHTML);
输出:
notClickable1= example1.com notClickable2= example2.com notClickable3= example3.com