[英]How can i ignore this tag directly for using only text information with using JSOUP?
[英]How I can replace “text” in the each tag using Jsoup
我有以下html:
<html>
<head>
</head>
<body>
<div id="content" >
<p>text <strong>text</strong> text <em>text</em> text </p>
</div>
</body>
</html>
如何使用Jsoup庫在每個標簽中將 “文本”替換為“單詞”。 我想看看:
<html>
<head>
</head>
<body>
<div id="content" >
<p>word <strong>word</strong> word <em>word</em> word </p>
</div>
</body>
</html>
感謝您的任何建議!
UPD:感謝您的回答,但我發現了一種通用的方式:
Element entry = doc.select("div").first();
Elements tags = entry.getAllElements();
for (Element tag : tags) {
for (Node child : tag.childNodes()) {
if (child instanceof TextNode && !((TextNode) child).isBlank()) {
System.out.println(child); //text
((TextNode) child).text("word"); //replace to word
}
}
}
Document doc = Jsoup.connect(url).get();
String str = doc.toString();
str = str.replace("text", "word");
試試吧..
快速搜索找到了以下代碼:
Elements strongs = doc.select("strong");
Element f = strongs.first();
Element l = strongs.last();1,siblings.lastIndexOf(l));
等等
首先,您要了解的是庫的工作方式以及它包含的功能,然后您要弄清楚如何使用該庫來完成所需的工作。 上面的代碼似乎允許您選擇一個較強的元素,這時您可以更新它的內部文本,但是我敢肯定,可以通過多種方法來實現相同的目的。
通常,大多數解析xml的庫都可以選擇文檔對象模型中的任何給定元素或元素的任何列表,並可以操縱元素本身或其內部文本,屬性等。
一旦獲得了使用其他庫的更多經驗,您的出發點便是查找庫的文檔,以了解該庫的功能。 如果您看到一個說它可以完成某件事的方法,那就是它所做的,並且您可以期望使用它來實現該目標。 然后,您無需解析有關Stack Overflow的問題,只需解析正在使用的庫的功能,並弄清楚如何使用它來完成所需的工作。
String html = "<html> ...";
Document doc = Jsoup.parse(html);
Elements p = doc.select("div#content > p");
p.html(p.html().replaceAll("text", "word"));
System.out.println(doc.toString());
div#content > p
表示id為content
的元素<div>
中的元素<p>
。
如果您只想替換<strong>text</strong>
:
Elements p = doc.select("div#content > p > strong");
p.html(p.html().replaceAll("text", "word"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.