【发布时间】:2015-12-21 21:15:51
【问题描述】:
准确地说,我有一个类,比如 A,我通过 rvest 中的 html_nodes 选择它。现在A可以有很多子类和很多html标签,比如links和img标签。我想从 A 中删除一些特定的类和标签,同时抓取其余数据。我不知道其余数据的类别。我知道我想把什么列入黑名单。
HTML(假设)。这个标签<div class="messageContent">在文档中最多重复25次,内容不同,但结构相同。
<div class="messageContent">
<article>
<blockquote class="messageText SelectQuoteContainer ugc baseHtml">
<div class="bbCodeBlock bbCodeQuote" data-author="Generic">
<aside>
<div class="attribution type">Generic said:
<a href="goto/post?id=32554#post-32754" class="AttributionLink">↑</a>
</div>
<blockquote class="quoteContainer"><div class="quote">I see what you did there.</div><div class="quoteExpand">Click to expand...</div></blockquote>
</aside>
</div><img src="styles/default/xenforo/clear.png" class="mceSmilieSprite mceSmilie9" alt=":o" title="Eek! :o"/> Really?
<aside>
<div class="attribution type">Generic said:
<a href="goto/post?id=32554#post-32754" class="AttributionLink">↑</a>
</div>
<blockquote class="quoteContainer"><div class="quote">I see what you did there.</div><div class="quoteExpand">Click to expand...</div></blockquote>
</aside>
<div class="messageTextEndMarker"> </div>
</blockquote>
</article>
</div>
所以,我正在抓取的页面包含多个这样的类。我愿意
posts <- page %>% html_nodes(".messageContent")
这给了我一个包含 25 个 html 节点的列表,每个节点都包含上述 html 内容的变体。
我想删除<aside> 和</aside> 标签中的所有内容(可能出现在帖子的多个位置),并通过html_text() %>% as.character() 捕获html 的其余部分
我可以用 rvest 做到这一点吗?
测试@Mirosław Zalewski 的解决方案。
test<- page %>% html_node(".messageContent") %>%
html_nodes(xpath='//*[not(ancestor::aside or name()="aside")]/text()')
这会返回页面中所有不在其中的元素。一点微调,导致我:
page %>% html_nodes(xpath='(//div[@class="messageContent"])[1]//*[not(ancestor::aside or name()="aside")]/text()') %>% html_text() %>% as.character()
迭代了 25 个类,这正是我所需要的。
【问题讨论】:
-
请向我们提供一个可重现的示例,以便为您提供帮助。