使用R和XML
包,我一直在尝试从具有与此类似结构的html文件中提取地址:
<!DOCTYPE html>
<body>
<div class='entry'>
<span class='name'>Marcus Smith</span>
<span class='town'>New York</span>
<span class='phone'>123456789</span>
</div>
<div class='entry'>
<span class='name'>Henry Higgins</span>
<span class='town'>London</span>
</div>
<div class='entry'>
<span class='name'>Paul Miller</span>
<span class='town'>Boston</span>
<span class='phone'>987654321</span>
</div>
</body>
</html>
我先做以下
library(XML)
html <- htmlTreeParse("test.html", useInternalNodes = TRUE)
root <- xmlRoot(html)
现在,我可以得到所有的名字:
xpathSApply(root, "//span[@class='name']", xmlValue)
## [1] "Marcus Smith" "Henry Higgins" "Paul Miller"
现在问题是所有地址都没有一些元素。在示例中,这是电话号码:
xpathSApply(root, "//span[@class='phone']", xmlValue)
## [1] "123456789" "987654321"
如果我这样做,我就无法将电话号码分配给合适的人。因此,我尝试首先提取整个地址簿条目,如下所示:
divs <- getNodeSet(root, "//div[@class='entry']")
divs[[1]]
## <div class="entry">
## <span class="name">Marcus Smith</span>
## <span class="town">New York</span>
## <span class="phone">123456789</span>
## </div>
从输出中我发现我已达到目标并且我可以得到,例如,对应于第一个条目的名称如下:
xpathSApply(divs[[1]], "//span[@class='name']", xmlValue)
## [1] "Marcus Smith" "Henry Higgins" "Paul Miller"
但即使divs[[1]]
的输出仅显示Marcus Smith
的数据,我也会收到所有三个名字。
这是为什么?我需要做什么,以这种方式提取地址数据,我知道name
,town
和phone
的哪些值属于一起?
答案 0 :(得分:2)
如果每个条目的商品数量不详,您可以将dplyr::bind_rows
或data.table::rbindlist
与rvest
结合使用,如下所示:
require(rvest)
require(dplyr)
# Little helper-function to extract all children and set Names
extract_info <- function(node){
child <- html_children(node)
as.list(setNames(child %>% html_text(), child %>% html_attr("class")))
}
doc <- read_html(txt)
doc %>% html_nodes(".entry") %>% lapply(extract_info) %>% bind_rows
给你:
name town phone
(chr) (chr) (chr)
1 Marcus Smith New York 123456789
2 Henry Higgins London NA
3 Paul Miller Boston 987654321
或者使用rbindlist(fill=TRUE)
代替bind_rows
,这会导致data.table
。或者使用purrr
代替map_df(as.list)
。
答案 1 :(得分:2)
purrr
通过嵌套节点并将结果列表破解为data.frame来使rvest
更有用:
library(rvest)
library(purrr)
html %>% read_html() %>%
# select all entry divs
html_nodes('div.entry') %>%
# for each entry div, select all spans, keeping results in a list element
map(html_nodes, css = 'span') %>%
# for each list element, set the name of the text to the class attribute
map(~setNames(html_text(.x), html_attr(.x, 'class'))) %>%
# convert named vectors to list elements; convert list to a data.frame
map_df(as.list) %>%
# convert character vectors to appropriate types
dmap(type.convert, as.is = TRUE)
## # A tibble: 3 x 3
## name town phone
## <chr> <chr> <int>
## 1 Marcus Smith New York 123456789
## 2 Henry Higgins London NA
## 3 Paul Miller Boston 987654321
当然,您可以用基数替换所有purrr
,但需要更多步骤。
答案 2 :(得分:1)
可能xpath表达式有问题,“//”总是转到根元素?
此代码适用于测试数据:
one.entry <- function(x) {
name <- getNodeSet(x, "span[@class='name']")
phone <- getNodeSet(x, "span[@class='phone']")
town <- getNodeSet(x, "span[@class='town']")
name <- if(length(name)==1) xmlValue(name[[1]]) else NA
phone <- if(length(phone)==1) xmlValue(phone[[1]]) else NA
town <- if(length(town)==1) xmlValue(town[[1]]) else NA
return(data.frame(name=name, phone=phone, town=town, stringsAsFactors=F))
}
do.call(rbind, lapply(divs, one.entry))
答案 3 :(得分:1)
丑陋的基础R + rvest解决方案(但我欺骗并使用管道以避免地狱般的嵌套parens或临时任务)来展示++ gd @ alistaire的解决方案:
library(rvest)
library(magrittr)
read_html("<!DOCTYPE html>
<body>
<div class='entry'>
<span class='name'>Marcus Smith</span>
<span class='town'>New York</span>
<span class='phone'>123456789</span>
</div>
<div class='entry'>
<span class='name'>Henry Higgins</span>
<span class='town'>London</span>
</div>
<div class='entry'>
<span class='name'>Paul Miller</span>
<span class='town'>Boston</span>
<span class='phone'>987654321</span>
</div>
</body>
</html>") -> pg
pg %>%
html_nodes('div.entry') %>%
lapply(html_nodes, css='span') %>%
lapply(function(x) {
setNames(html_text(x), html_attr(x, 'class')) %>%
as.list() %>%
as.data.frame(stringsAsFactors=FALSE)
}) %>%
lapply(., unlist) %>%
lapply("[", unique(unlist(c(sapply(., names))))) %>%
do.call(rbind, .) %>%
as.data.frame(stringsAsFactors=FALSE)