我有如下一段HTML的:Jsoup標籤名()給出了錯誤的標籤
<p>
<a href="http://www.today.com/video/jill-martin-rescues-savannah-guthrie-from-her-guest-room-mess-604921923959" rel="nofollow"> Jill Martin rescues Savannah Guthrie from her guest room mess </a>
<a href="http://www.today.com/video/4-simple-ways-to-clear-your-clutter-this-year-596741699678" rel="nofollow"> 4 simple ways to clear your clutter this year </a>
<a href="http://www.today.com/video/staying-home-on-new-years-eve-great-ideas-to-celebrate-at-home-594027587814" rel="nofollow"> Staying home on New Year's Eve? Great ideas to celebrate at home </a>
<a href="http://www.today.com/video/heres-how-to-set-a-functional-christmas-table-591622211749" rel="nofollow"> Here's how to set a functional Christmas table </a>
</p>
這件作品是從網頁http://www.today.com/home/decorating-ideas-david-bromstad-shares-tips-living-luxury-less-t70861
而且一段代碼:
Document document = Jsoup.connect("http://www.today.com/home/decorating-ideas-david-bromstad-shares-tips-living-luxury-less-t70861").get();
String tag = null;
for (Element element : document.select("*")) {
tag = element.tagName();
if ("a".equalsIgnoreCase(tag)) {
LOGGER.info("element : {}; nextElementSibling: {}", element.ownText(), element.nextElementSibling());
}
if (StringUtils.containsIgnoreCase(element.ownText(), "Jill Martin rescues Savannah")) {
LOGGER.info("element : {}; nextElementSibling: {}", element.ownText(), element.nextElementSibling());
LOGGER.info("tag : {}; nextNodeSibling: {}", tag, element.nextSibling());
LOGGER.info("element : {}; previousElementSibling: {}", element.ownText(), element.previousElementSibling());
}
}
輸出我得到:
element : Jill Martin rescues Savannah Guthrie from her guest room mess; nextElementSibling: null
tag : h2; nextNodeSibling:
element : Jill Martin rescues Savannah Guthrie from her guest room mess; previousElementSibling: null
有許多的問題:
- 從主HTML源有標記爲
a
許多元素,但沒有從小型HTML一塊我覈對 - 看來
<a>
被捕獲爲<h2>
element.nextElementSibling()
在大多數情況下爲空
但是,如果單獨針對小塊進行測試,問題就會消失。因此,看起來Jsoup在出現在更大的HTML源代碼中時無法正確識別標籤。
任何想法爲什麼?
謝謝。
EDIT 2
演習背後的用意是清理網頁。這就是爲什麼我遍歷整個HTML,而不是像@Stephan所建議的特定部分。我只挑選了一個看起來有問題的特定部分。
但是在檢查@luksch的迴應之後,我重新查看了原始的HTML並找到了從中拍攝的異常情況。代碼全面查看所有標籤,但給出例外a
。在的主要來源,我們有article
隨後a
,figure
(包含i
,img
,img
,small
,small
),h2
。這個問題似乎像所有的標籤(a
除外)都被刪除(按要求工作),但他們的text
被留下。這就是爲什麼我最終留下了這是不是原來的HTML源代碼。
的吉爾·馬丁從她的客房亂搶救薩凡納格思裏是<h2>
文本,但<h2>
是被刪除,留下它的文本後面。有趣的是,Jsoup仍然認爲文本來自h2
,儘管最終輸出沒有h2
。
該片段是大型代碼的一部分。原始鏈接是「http:// www.today.com/home/decorating-ideas-david-bromstad-shares-tips-living-luxury-less-t70861」。因此,較大的文檔應該是'Document doc = Jsoup.connect(「http://www.today.com/home/decorating-ideas-david-bromstad-shares- tips-living-luxury-less-t70861」) .get();' –
URL給了我一個404 – luksch
@luksch,當我複製粘貼時,它出現錯誤。這是調用:Jsoup.connect(「http://www.today.com/home/decorating-ideas-david-bromstad-shares-tips-living-luxury-less-t70861」).get();. '生活'之後的單詞是'奢侈',但複製粘貼錯誤。 –