我找不到任何方法來使用com.gargoylesoftware.htmlunit.html僅從根元素提取文本內(nèi)容。這是一些例子:<td> W 03:10 PM-04:25 PM <strong> <br> Hybrid (50%+ in-person) </strong></td>我想從根元素(在本例中為“td”)中提取文本內(nèi)容,但它也從子元素中提取文本內(nèi)容,這是我不想要的部分:private void extractTextContent(HtmlElement htmlElement) { String content = htmlElement.getTextContent(); System.out.println(content);}輸出:W 03:10 PM-04:25 PMHybrid (50%+ in-person)期望的輸出:W 03:10 PM-04:25 PM我嘗試使用其他方法調(diào)用“asText()”,但這并沒有給我想要的輸出。我找不到任何使用com.gargoylesoftware.htmlunit.html有相同問題的人。有沒有什么方法/方法可以僅從根元素中提取文本內(nèi)容?編輯: 謝謝您的回答。我使用刪除子節(jié)點的相同想法來獲得我想要的輸出。下面是java的語法:private void extractTextContent(HtmlElement htmlElement) { DomNode child = htmlElement.getLastElementChild(); String tagname = ""; if(child != null) { tagname = child.getTextContent(); htmlElement.removeChild(tagname, 0); } String content = htmlElement.getTextContent();}
1 回答

慕運維8079593
TA貢獻1876條經(jīng)驗 獲得超5個贊
您可以嘗試在獲取 textContent 之前刪除子節(jié)點。
private void extractTextContent(HtmlElement htmlElement) {
? ? DomNode child = htmlElement.getLastElementChild();
? ? String tagname = "";
? ? if(child != null) {
? ? ? ? tagname = child.getTextContent();
? ? ? ? htmlElement.removeChild(tagname, 0);
? ? }
? ? String content = htmlElement.getTextContent();
}
- 1 回答
- 0 關(guān)注
- 99 瀏覽
添加回答
舉報
0/150
提交
取消