gpt4 book ai didi

r - 如何从 html 节点中删除 2-3 个元素并抓取其余元素?

转载 作者:行者123 更新时间:2023-12-01 08:08:15 25 4
gpt4 key购买 nike

准确地说,我有一个类,比如 A,我通过 rvest 中的 html_nodes 选择它。现在 A 可以有很多子类和很多 html 标签,比如 linksimg 标签。我想从 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">&uarr;</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">&uarr;</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">&nbsp;</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()')

这会返回页面中所有不在 aside 内的元素。一些微调,让我:

page %>% html_nodes(xpath='(//div[@class="messageContent"])[1]//*[not(ancestor::aside or name()="aside")]/text()') %>% html_text() %>% as.character()

迭代了 25 个类,这正是我所需要的。

最佳答案

使用 XPath,您可以选择所有不是 <aside> 的节点或 <aside> 的后代:

page %>% html_node(".messageContent") %>%
html_nodes(xpath='//*[not(ancestor::aside or name()="aside")]')

不幸的是,这也会匹配包含 <aside> 的元素.如果你把它传递给 html_text() ,它将返回 <aside>无论如何都是文本内容。

这可以通过在查询中添加另一个条件来克服。这种情况的一个很好的候选者是“一切都是文本节点”:

page %>% html_node(".messageContent") %>%
html_nodes(xpath='//*[not(ancestor::aside or name()="aside")]/text()')

实际上,/text()将只返回文本节点,这几乎允许您跳过 html_text()完全调用。但是由于许多文本节点是可疑的(只包含空白字符)并且这个函数有 trim内置,您可能会考虑调用它。

请注意,此解决方案还将跳过任何非文本内容,例如图像引用(可能包括表情)。您最初的提议也会这样做,但我不清楚您是否有意这样做。

关于r - 如何从 html 节点中删除 2-3 个元素并抓取其余元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34404447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com