2017-12-29 20 views
1

rvest 및 selectorgadget을 사용하여 여러 링크에서 r으로 일부 테니스 통계를 다 써 버리려합니다. 내가 긁은 페이지는 http://www.atpworldtour.com/en/scores/archive/stockholm/429/2017/results이며 "http://www.atpworldtour.com/en/scores/2017/429/MS001/match-stats"와 같은 29 개의 링크가 있습니다. 모든 링크는 동일하게 보이지만 MS001-MS029에서 변경됩니다. 아래 코드를 사용하면 처음 9 개 링크만으로 원하는 결과를 얻을 수 있습니다. 나는 문제를 보지만 그것을 고치는 법을 모른다. 첫 번째 9 개의 링크는 두 배 00이고 나머지는 한 번 0입니다. 10 번째 링크는 MS010이어야합니다. 어떤 도움이 많이 감사합니다.웹에서 여러 링크로 r을 긁음

library(xml) 
library(rvest) 
library(stringr) 

round <- 1:29 
urls <- paste0("http://www.atpworldtour.com/en/scores/2017/429/MS00", round, 
"/match-stats") 

aces <- function(url) { 
url %>% 
read_html() %>% 
html_nodes(".percent-on:nth-child(3) .match-stats-number-left span") %>% 
html_text() %>% 
as.numeric() 
} 

results <- sapply(urls, aces) 
results 
$`http://www.atpworldtour.com/en/scores/2017/429/MS001/match-stats` 
[1] 9 

$`http://www.atpworldtour.com/en/scores/2017/429/MS002/match-stats` 
[1] 8 

$`http://www.atpworldtour.com/en/scores/2017/429/MS003/match-stats` 
[1] 5 

$`http://www.atpworldtour.com/en/scores/2017/429/MS004/match-stats` 
[1] 4 

$`http://www.atpworldtour.com/en/scores/2017/429/MS005/match-stats` 
[1] 8 

$`http://www.atpworldtour.com/en/scores/2017/429/MS006/match-stats` 
[1] 9 

$`http://www.atpworldtour.com/en/scores/2017/429/MS007/match-stats` 
[1] 2 

$`http://www.atpworldtour.com/en/scores/2017/429/MS008/match-stats` 
[1] 9 

$`http://www.atpworldtour.com/en/scores/2017/429/MS009/match-stats` 
[1] 5 

$`http://www.atpworldtour.com/en/scores/2017/429/MS0010/match-stats` 
numeric(0) 

답변

1

sprintf() 함수를 통해 서식이 지정된 문자열에서 선행 0을 생성 할 수 있습니다.

ids <- 1:29 
urlList <- sapply(ids,function(x){  
sprintf("%s%03d%s","http://www.atpworldtour.com/en/scores/2017/429/MS", 
     x,"/match-stats") 
}) 
# print a few items 
urlList[c(1,9,10,29)] 

... 그리고 출력 : 이것은 잘 작동

> urlList[c(1,9,10,29)] 
[1] "http://www.atpworldtour.com/en/scores/2017/429/MS001/match-stats" 
[2] "http://www.atpworldtour.com/en/scores/2017/429/MS009/match-stats" 
[3] "http://www.atpworldtour.com/en/scores/2017/429/MS010/match-stats" 
[4] "http://www.atpworldtour.com/en/scores/2017/429/MS029/match-stats" 
> 
+0

, 감사합니다. 실제로 3 개의 링크 MS016, MS020 및 MS027은 존재하지 않습니다. 후속 조치를 취하고 1시 29 분 사이에 존재하는 링크 만 긁는 방법이 있는지 물어볼 수 있습니까? – mrsama

+0

ids <- c (1 : 15,17 : 19,21 : 26,28 : 29)를 사용하여 URL을 생성하십시오. –

+0

@mrsama - 내가 제공 한 솔루션을 사용할 수 있었다면 제 대답을 받아주십시오. –

관련 문제