将html结果保存到txt或html文件

时间:2015-12-25 13:22:53

标签: r

我有一个带html代码的变量。

这里是R控制台中的代码变量outpout:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>

我尝试将内容保存到txt文件

 write.table(code, file='C:/Users/Desktop/code_result.txt')

但它堆积了这个错误:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  c("cannot coerce class \"c(\"HTMLInternalDocument\", \"HTMLInternalDocument\", \"XMLInternalDocument\", \" to a data.frame", "cannot coerce class \"\"XMLAbstractDocument\")\" to a data.frame")

4 个答案:

答案 0 :(得分:4)

一个选项是saveXML,另一个选项是sink()

pacman::p_load(scrapeR) # or require() or library()
f = system.file("exampleData", "mtcars.xml", package="XML")
doc = xmlTreeParse(f, useInternalNodes = TRUE)
sink("your.file.txt")
doc
sink()

答案 1 :(得分:4)

这是一个简单的解决方案(虽然我更喜欢使用包XML,如您对问题的评论中所建议的那样):

code <- "<!DOCTYPE html>
  <html>
  <body>

  <h1>My First Heading</h1>

  <p>My first paragraph.</p>

  </body>
</html>"

注意:如果您已经有一个包含上述文本的对象, 您可以将其转换为字符串,因此以下代码适用:

code <- paste(as.character(code), collapse = "\n")

write.table(code, 
            file='C:/Users/dsargsy/Desktop/code_result.html', 
            quote = FALSE,
            col.names = FALSE,
            row.names = FALSE)

答案 2 :(得分:1)

对于所有读/写操作来说非常舒适的软件包是rio软件包。

library(rio)
export(html_code,
       file="html_code_result.html",
       format="html"
      )

使用这种语法,rio :: export()函数支持许多其他格式, 包括

  • excel
  • matlab
  • spss
  • json

等等。 这也非常快!

答案 3 :(得分:0)

仅使用基数的最简单解决方案必须是:

writeLines(text = code, con = 'C:/Users/Desktop/code_result.txt')
相关问题