7

I'd like to do exactly what xml2::xml_text() or rvest::html_text() do but preserve the tags instead of replacing e.g. <br> with \n. The objective is to e.g. scrape a web page, extract the nodes I want, and store the plain HTML in a variable, much like write_html() would store it in a file.

How can I do this?

4
  • When asking for help, you should include a simple reproducible example with sample input and desired output that can be used to test and verify possible solutions.
    – MrFlick
    Sep 14, 2018 at 19:55
  • 1
    @MrFlick I am aware, but here I'm asking a very general question and thus believe the description I provided should suffice. The solution I'm looking for is a single function already implemented in xml2, only without discarding the tags, or what another function does, only with output to another variable instead of an external file. Sep 14, 2018 at 20:11
  • So you want to keep the XML as a string with no parsing? Why can't you just read it as a string? Or do you want to traverse/modify the tree with xml2 and then get the output of specific parts as a raw, unparsed string?
    – divibisan
    Sep 14, 2018 at 20:53
  • @divibisan Indeed. Because the data structure is a list with external pointers and I don't know how to convert that to a string. Sep 14, 2018 at 20:55

1 Answer 1

9

Ironically, it turns out that as.character() works just fine.

Therefore:

library(rvest)
html <- read_html("http://stackoverflow.com")

res <– html %>%
         html_node("h1") %>%
         as.character()

> res

[1] "<h1 class=\"-title\">Learn, Share, Build</h1>"

This is the desired output in my current use case.

On the other hand, for comparison if one needs to strip the tags:

res <- html %>%
         html_node("h1") %>%
         html_text()

> res
[1] "Learn, Share, Build"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.