8

I am trying to scrape a table in R that I have been given in html form. Rvest was super useful in getting all of the text out of the table, but I would like to keep the inline styling that occurs in its HTML form.

For example, text in the table might be

"This is a sentence <BR> this is another sentence"

I would like to preserve the BR

I've tried reading in the whole table:

my_table <- my_table_html %>% 
html_nodes("table") %>% 
html_table(fill=TRUE) 

I've also tried selecting specific columns in the table:

my_column <- my_table_html %>% 
html_nodes(".Tabletitle:nth-child(2)") %>%
html_text()

Any ideas would be much appreciated

Miles
  • 81
  • 4

1 Answers1

11
library(rvest)

pg <- read_html("This is a sentence <BR> this is another sentence")

xml_find_all(pg, ".//br") %>% xml_add_sibling("p", "\n")

xml_find_all(pg, ".//br") %>% xml_remove()

html_text(pg)
## [1] "This is a sentence \n this is another sentence"
hrbrmstr
  • 71,487
  • 11
  • 119
  • 180