我有如下一段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();. '生活'之后的单词是'奢侈',但复制粘贴错误。 –