【问题标题】:Can rvest keep inline html tags such as <br> using html_table?rvest 是否可以使用 html_table 保留内联 html 标签,例如 <br>?
【发布时间】:2015-09-04 11:05:00
【问题描述】:

我正在尝试在 R 中抓取我以 html 形式给出的表格。 Rvest 在将所有文本从表格中取出时非常有用,但我想保留其 HTML 表单中出现的内联样式。

例如,表格中的文本可能是

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

我想保留 BR

我已经尝试在整个表格中阅读:

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

我也尝试过选择表格中的特定列:

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

任何想法将不胜感激

【问题讨论】:

  • 您找到答案了吗?我希望用 html_text() 做同样的事情。
  • Python中有一个解决方案:stackoverflow.com/a/18661076/635806 -- 或许可以适配rvest/xml2。

标签: html r rvest


【解决方案1】:
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"

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多