我使用R
它的包xml2
来解析html
文档。我提取了一个html
文件,如下所示:
text <- ('<div>
<p><span class="number">1</span>First <span class="small-accent">previous</span></p>
<p><span class="number">2</span>Second <span class="accent">current</span></p>
<p><span class="number">3</span>Third </p>
<p><span class="number">4</span>Fourth <span class="small-accent">last</span> A</p>
</div>')
我的目标是从文本中提取信息并将其转换为数据框,如下所示:
number label text_of_accent type_of_accent
1 1 First previous small-accent
2 2 Second current accent
3 3 Third
4 4 Fourth A last small-accent
我尝试了以下代码:
library(xml2)
library(magrittr)
html_1 <- text %>%
read_html() %>%
xml_find_all( "//span[@class='number']")
number <- html_1 %>% xml_text()
label <- html_1 %>%
xml_parent() %>%
xml_text(trim = TRUE)
text_of_accent <- html_1 %>%
xml_siblings() %>%
xml_text()
type_of_accent <- html_1 %>%
xml_siblings() %>%
xml_attr("class")
不幸的是,label
,text_of_accent
没有type_of_accent
像我预期的那样被提取:
label
[1] "1First previous" "2Second current" "3Third" "4Fourth last A"
text_of_accent
[1] "previous" "current" "last"
type_of_accent
[1] "small-accent" "accent" "small-accent"
是否有可能只使用xml2
或我需要一些额外的工具来实现我的目标?至少可以提取文本片段label
吗?