[英]How to select text in HTML tag without a tag around it (JSoup)
我想在strong-tag中選擇文本,但不包含div ...
是否有可能直接使用jsoup?
我嘗試選擇(不起作用,選擇strong-tag內的完整內容):
Elements selection = htmlDocument.select("strong").select("*:not(.dontwantthatclass)");
HTML:
<strong>
I want that text
<div class="dontwantthatclass">
</div>
</strong>
您正在尋找ownText()方法。
String txt = htmlDocument.select("strong").first().ownText();
看看jsoup必須處理的各種方法https://jsoup.org/apidocs/org/jsoup/nodes/Element.html 。 您可以使用remove()
, removeChild()
等。您可以做的一件事是使用正則表達式。 這是一個匹配開始和結束標記的示例正則表達式,也附加了</br>
標簽https://www.debuggex.com/r/1gmcSdz9s3MSimVQ
所以你可以這樣做
selection.replace(/<([^ >]+)[^>]*>.*?<\/\1>|<[^\/]+\/>/ig, "");
您可以進一步修改此正則表達式以匹配大多數情況。
你可以做的另一件事是,使用javascript或vbscript進一步處理你的變量: -
Elements selection = htmlDocument.select("strong")
jquery代碼在這里: -
var removeHTML = function(text, selector) {
var wrapped = $("<div>" + text + "</div>");
wrapped.find(selector).remove();
return wrapped.html();
}
使用正則表達式,您可以使用jsoup的ownText()方法來獲取和刪除不需要的字符串。
我猜你正在使用jQuery,所以你可以在“strong”元素上使用“innerText”屬性:
var selection = htmlDocument.select("strong")[0].innerText;
https://jsfiddle.net/scratch_cf/8ds4uwLL/
PS:如果你想將檢索到的文本包裝成“強”標簽,我想你必須建立一個像$('<strong>retrievedText</strong>');
這樣的新元素$('<strong>retrievedText</strong>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.