简体   繁体   中英

How to convert an HTML R object to character?

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.

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")

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")

as(page, "character")替换as.character(page) as(page, "character")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM