r-Web刮取不均匀的非表内容-当一个标题有多个值时出现问题



我正试图从cricinfo网站上板球运动员的个人资料中获取他们的基本球员信息。以下是玩家个人资料页面的示例:https://www.espncricinfo.com/player/shaun-marsh-6683

最终,我想在R中编写一个函数,以提取概览选项卡顶部的信息(全名、出生、年龄等(,并将信息放入R中的数据帧中。然后,我有另一个函数可以为多个感兴趣的玩家这样做。

然而,有两个主要问题:第一,并非所有玩家的概览页面上都有相同的信息类别。因此,我需要导入每个玩家的类别标题(例如全名、出生、年龄等(以及相应的值。我使用R中的rvest完成了这项工作,代码如下:

player_info <- content %>%
html_nodes(".player_overview-grid") %>%
html_nodes(".player-card-description.gray-900") %>% 
html_text()

player_cats <- content %>% 
html_nodes(".player_overview-grid") %>% 
html_nodes(".player-card-heading") %>% 
html_text()
newplayer <- data.frame(player_cats, player_info)

这给了大多数玩家想要的结果,但遇到了一个我不知道如何解决的问题。一些玩家在给定的标题中有两个值;例如,在上面给出的链接中,玩家有两个关系(兄弟和父亲(,因此这意味着player_catsplayer_info向量具有不同的长度。

请有人帮我解决这个问题。我认为我需要以某种方式将类别及其值提取为成对的,而不是单独的,如果这有意义的话。如果有多个条目,我很乐意提取类别中的第一个值,或者在R的最终数据帧中多次包括类别标题。两者都可以。

对不起,如果这是一个简单的问题,我对此很陌生。非常感谢

编辑:

假设我将该函数应用于该玩家的页面https://www.espncricinfo.com/player/wes-agar-959833,则输出是所需的,因为每个类别只有一个条目。也就是说,它给了我以下数据帧:如下图1所示,该玩家的信息类别及其值的数据帧

但是,当我尝试将函数应用于列出的原始配置文件时,会出现问题:https://www.espncricinfo.com/player/shaun-marsh-6683.我得到了一个错误,因为有9个类别,但有10个条目,因此无法使用rbind。见图2、3、4。我需要找到一种方法来抓取每个值属于哪个类别,这样我就可以在R中的数据帧中复制类别标题;GR Marsh";在RH列中。

一种解决方法是对每个类别使用html_text2xpath

library(rvest)
library(dply)
url = "https://www.espncricinfo.com/player/shaun-marsh-6683"
#create an empty dataframe to store results 
df = vector() 

for(i in 1:9){
#creating xpath for each of the nine category
nod = paste0('//*[@id="main-container"]/div[1]/div/div[2]/div/div[2]/div[2]/div[1]/div/div[1]/div[', i, ']')
df1 = url %>%
read_html() %>% 
html_nodes(xpath =nod) %>% 
html_text2()
#now we split the result into columns
df1= do.call(rbind, str_split(df1, "n"))
df = rbind.data.frame(df, df1)
}
V1 V2                                         V3
1     Full Name                            Shaun Edward Marsh
2          Born    July 09, 1983, Narrogin, Western Australia
3           Age                                      38y 147d
4     Nicknames                                           Sos
5 Batting Style                                 Left hand bat
6 Bowling Style                        Slow left arm orthodox
7  Playing Role                              Top order batter
8        Height                                        1.84 m
9     relations          GR Marsh (father),MR Marsh (brother)

相关内容

最新更新