【问题标题】:Excluding Nodes RVest排除节点 RVest
【发布时间】:2017-03-27 04:43:15
【问题描述】:

我正在使用 RVest 抓取博客文本,并且正在努力寻找一种简单的方法来排除特定节点。以下拉取文字:

AllandSundry_test <- read_html
("http://www.sundrymourning.com/2017/03/03/lets-go-back-to-commenting-on-the-weather/")

testpost <- AllandSundry_test %>% 
html_node("#contentmiddle") %>%
html_text() %>%
as.character()

我想排除 ID 为“contenttitle”和“commentblock”的两个节点。下面,我尝试使用标签“commentblock”排除 cmets。

 testpost <- AllandSundry_test %>% 
   html_node("#contentmiddle") %>%
   html_node(":not(#commentblock)")
   html_text() %>%
   as.character()

当我运行它时,结果只是日期——所有其余的文本都消失了。有什么建议吗?

我花了很多时间寻找答案,但我是 R(和 html)的新手,所以如果这是显而易见的事情,我感谢你的耐心。

【问题讨论】:

  • 您能否提供您要从中抓取的网址?我只是无法理解你的问题的要点。
  • 感谢您的回复。我用我正在使用的确切示例编辑了这个问题。感谢您的帮助。

标签: r web-scraping rvest


【解决方案1】:

你快到了。您应该使用html_nodes 而不是html_node

html_node 检索它遇到的第一个元素,而html_nodes 将页面中的每个匹配元素作为列表返回。
toString() 函数将字符串列表合并为一个。

library(rvest)

AllandSundry_test <- read_html("http://www.sundrymourning.com/2017/03/03/lets-go-back-to-commenting-on-the-weather/")

testpost <- AllandSundry_test %>% 
  html_nodes("#contentmiddle>:not(#commentblock)") %>% 
  html_text %>%
  as.character %>%
  toString

testpost
#> [1] "\n\t\tMar\n\t\t3\n\t, Mar, 3, \n\t\tLet's go back to 
#> commenting on the weather\n\t\t\n\t\t, Let's go back to commenting on 
#> the weather, Let's go back to commenting on the weather, I have just 
#> returned from the grocery store, and I need to get something off my chest. 
#> When did "Got any big plans for the rest of the day?" become 
#> the default small ...<truncated>

您仍然需要稍微清理一下字符串。

【讨论】:

  • 因此,出于某种原因,它似乎仍在拾取 cmets。谢谢,这个特定网站上的 html 看起来很乱。
  • 你是对的,我很确定我没有真正检查。我现在不确定为什么这不起作用。无论如何,用可行的解决方案编辑答案。
  • 谢谢!像魅力一样工作。
【解决方案2】:

看起来 GGamba 确实为你解决了这个问题——但是,在我的机器上,我必须删除 #contentmiddle 之后的 >。因此,本节改为:

html_nodes("#contentmiddle:not(#commentblock)")

祝你好运! 杰西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2022-12-06
    • 2019-10-26
    相关资源
    最近更新 更多