How to convert an HTML R object to character?

2019-05-24 17:11发布

Here's my reproducible example:

library(rvest)
page <- html("http://google.com")
class(page)
page
> as.character(page)
Error in as.vector(x, "character") : 
  cannot coerce type 'externalptr' to vector of type 'character'

How can I convert page from an html class to a character vector so I can store it somewhere?

The html functions like html_text or html_attr don't give me the whole source. I would like to store it so I can later re-load it with html().

Thanks.

标签: xml r rvest httr
3条回答
我命由我不由天
2楼-- · 2019-05-24 17:19

Replace as.character(page) with as(page, "character")

查看更多
干净又极端
3楼-- · 2019-05-24 17:27

Or, you can just use saveXML from the XML package to handle the HTML/XML object directly without other machinations.

library(rvest)
library(XML)

pg <- html("http://dds.ec/")
saveXML(pg, "output.html")
查看更多
Fickle 薄情
4楼-- · 2019-05-24 17:37

To save directly to a text file:

capture.output(page, file="file.html")

To store as a string:

htmltxt <- paste(capture.output(page, file=NULL), collapse="\n")
查看更多
登录 后发表回答