首页 > 解决方案 > R:html_nodes 在站点上复制内容

问题描述

我在 html_nodes 复制网站上的内容时遇到了一个奇怪的问题。

这是基本代码:

# I bring in a sample URL with a lot of CSS and Javascript
address <- "https://www.speedtest.net/"
content <- read_html(URLencode(address))
content %>%
    # I want to analyze the words on the page, so I bring in the body.
    html_nodes("body") %>%
    # I don't want Javascript and CSS cluttering the analysis, so I remove them
    html_nodes(":not(script)") %>%
    html_nodes(":not(style)") %>%
    html_text

html_nodes(":not(script)") 有效地消除了 Javascript 的混乱。但是,由于某种原因,它还复制了网站上的每一行文本,因此我的最终输出如下所示:

网络状态 网络状态 隐私政策 隐私政策 使用条款 使用条款 不要出售我的个人信息 不要出售我的个人信息

我觉得这只是我的一个语法错误。谁知道怎么修它?还是有更聪明的方法来达到同样的结果?

提前致谢!

标签: rweb-scrapingrvest

解决方案


你可以这样考虑:

address <- "https://www.speedtest.net/"
content <- read_html(URLencode(address))
content_data <- 
  content %>%
  html_nodes(xpath = "//body/descendant-or-self::*[not(name()='script' or name()='style')]/text()") %>%
  html_text(trim = T) %>%
  .[. != ""]

推荐阅读