r - 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 的混乱。但是,由于某种原因,它还复制了网站上的每一行文本,因此我的最终输出如下所示:
网络状态 网络状态 隐私政策 隐私政策 使用条款 使用条款 不要出售我的个人信息 不要出售我的个人信息
我觉得这只是我的一个语法错误。谁知道怎么修它?还是有更聪明的方法来达到同样的结果?
提前致谢!
解决方案
你可以这样考虑:
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) %>%
.[. != ""]
推荐阅读
- google-analytics - 跟踪从合作伙伴网站到我的网站的点击次数
- wildfly - Wildfly-15.0.1.Final 与 OpenJdk-11 的部署因 org.jboss.modules.ModuleNotFoundException 错误而失败
- javascript - 如何在 php 中的 json_decode() 中显示特殊字符,如“Ñ”
- java - 需要有关弹性搜索自动化的信息
- java - 禁止登录 SwaggerGen
- osgi - Adobe AEM/OSGI:如何从任何类访问 OSGI 服务?
- bash - 在 macOS 上更改 .profile 中的陷阱后无法消除错误
- ios - CAGradientLayer 上均匀分布的颜色
- typescript - 如何在打字稿中将 Blob 类型转换为字节数组?
- html - 从跨域加载 vtt 的问题