Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can rvest keep inline html tags such as <br> using html_table?

Tags:

html

r

rvest

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

like image 752
Miles Avatar asked Jun 18 '15 17:06

Miles


1 Answers

library(rvest)
library(xml2)

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"
like image 180
hrbrmstr Avatar answered Nov 16 '22 04:11

hrbrmstr