R - 如何从XML Nodeset中提取项目?

时间:2017-04-24 22:02:26

标签: html r xml web-scraping nodes

我有一个438个投手名称的列表,如下所示(在XML Nodeset中):

> pitcherlinks[[1]]
<td class="left " data-append-csv="abadfe01" data-stat="player" csk="Abad,Fernando0.01">
  <a href="/players/a/abadfe01.shtml">Fernando Abad</a>*
</td> 

> pitcherlinks[[2]]
<td class="left " data-append-csv="adlemti01" data-stat="player" csk="Adleman,Tim0.01">
  <a href="/players/a/adlemti01.shtml">Tim Adleman</a>
</td> 

如何提取Fernando Abad等名称以及/players/a/abadfe01.shtml

等相关链接

1 个答案:

答案 0 :(得分:1)

由于您有一个列表,因此使用apply函数遍历列表。每个函数使用read_html使用CSS选择器a解析列表中的hmtl片段以查找锚点(链接)。名称来自html_text,链接位于属性href

library(rvest)
pitcherlinks <- list()
pitcherlinks[[1]] <- 
'<td class="left " data-append-csv="abadfe01" data-stat="player" csk="Abad,Fernando0.01">
  <a href="/players/a/abadfe01.shtml">Fernando Abad</a>*
    </td>'

pitcherlinks[[2]] <- 
  '<td class="left " data-append-csv="adlemti01" data-stat="player" csk="Adleman,Tim0.01">
    <a href="/players/a/adlemti01.shtml">Tim Adleman</a>
      </td>'

names <- sapply(pitcherlinks, function(x) {x %>% read_html() %>% html_nodes("a") %>% html_text()})
links <- sapply(pitcherlinks, function(x) {x %>% read_html() %>% html_nodes("a") %>% html_attr("href")})

names
# [1] "Fernando Abad" "Tim Adleman"  
links
# [1] "/players/a/abadfe01.shtml"  "/players/a/adlemti01.shtml"