向文本元素添加空格

met*_*dds 2 r rvest xml2

有没有一种方法可以向每个包含文本的元素添加空格?对于此示例:

movie <- read_html("http://www.imdb.com/title/tt1490017/") 
cast <- html_nodes(movie, "#titleCast span.itemprop")
cast %>% html_structure()
[[1]]
<span.itemprop [itemprop]>
  {text}

[[2]]
<span.itemprop [itemprop]>
  {text}
Run Code Online (Sandbox Code Playgroud)

我想使用之前为每个文本元素添加尾随空格html_text()。我还有另一个用例,我想html_text()在文档层次结构中使用更高的级别。结果是将多个文本合并到一个向量元素中。这使得无法推断相应部分的开始和结束。

Ren*_*rop 5

你的意思是这样吗?

doc <- minimal_html("Hello<p>World</p>") 
doc %>% html_text # HelloWorld
doc %>% html_text_collapse(" ") # Hello World
Run Code Online (Sandbox Code Playgroud)

如果是这样,则代码如下:

require(stringi)
require(rvest)

html_text_collapse <- function(x, collapse = " ", trim = TRUE){
  text <- html_text(html_nodes(x, xpath = ".//text()[normalize-space()]"))
  if (trim) {
    text <- stri_trim_both(text)
  }
  paste(text, collapse = collapse)
}
Run Code Online (Sandbox Code Playgroud)