【问题标题】:Web scrape multiple links with r网页用 r 抓取多个链接
【发布时间】:2017-12-29 22:49:44
【问题描述】:

我正在尝试使用 rvest 和 selectorgadget 从多个链接中用 r 抓取一些网球统计数据。我从 http://www.atpworldtour.com/en/scores/archive/stockholm/429/2017/results 抓取的页面有 29 个链接,如下所示:“http://www.atpworldtour.com/en/scores/2017/429/MS001/match-stats”。所有链接看起来都一样,但从 MS001-MS029 有所不同。使用下面的代码,我只使用前 9 个链接得到了想要的结果。我看到了问题,但不知道如何纠正它。前 9 个链接有双 00,其余的有单 0。第 10 个链接应该是 MS010。非常感谢任何帮助。

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)

【问题讨论】:

    标签: r web-scraping


    【解决方案1】:

    可以通过sprintf() 函数在格式化字符串中生成前导零。

    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"
    > 
    

    【讨论】:

    • 这很好用,谢谢。实际上 3 个链接 MS016、MS020 和 MS027 不存在。我可以跟进并询问是否有办法只抓取 1:29 之间存在的链接?
    • 当然,使用 ids
    • @mrsama - 如果您能够使用我提供的解决方案,请接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 2017-12-24
    • 1970-01-01
    • 2020-08-08
    • 2021-04-25
    • 1970-01-01
    • 2016-08-09
    • 2022-01-21
    相关资源
    最近更新 更多