如何使用 R 识别网页上最新的可下载文件?

问题描述

我正在尝试定期检查添加页面 https://github.com/mrc-ide/global-lmic-reports/tree/master/data 的最新可下载文件的日期,其中文件名类似于 2021-05-22_v8.csv.zip

Using R to scrape the link address of a downloadable file from a web page? 中提到了一个代码片段,可以通过调整使用,并标识网页上一个或最早可下载文件的日期,如下所示。

library(rvest)
library(stringr)
library(xml2)

page <- read_html("https://github.com/mrc-ide/global-lmic-reports/tree/master/data")

page %>%
  html_nodes("a") %>%       # find all links
  html_attr("href") %>%     # get the url
  str_subset("\\.csv.zip") %>% # find those that end in .csv.zip
  .[[1]]                    # look at the first one

返回: [1] "/mrc-ide/global-lmic-reports/blob/master/data/2020-04-28_v1.csv.zip"

问题是识别最新 .csv.zip 文件日期的代码是什么?例如,截至 2021 年 6 月 1 日检查的 2021-05-22_v8.csv.zip。

目的是,如果该日期(即 2021-05-22)是 > 我在 https://github.com/pourmalek/covir2 中创建的最新更新(例如 https://github.com/pourmalek/covir2/tree/main/20210528 中的 IMPE 20210522),那么新的更新需要被创建。

解决方法

您可以将链接转换为日期并使用 which.max 获取最新的链接。

library(rvest)
library(stringr)
library(xml2)

page <- read_html("https://github.com/mrc-ide/global-lmic-reports/tree/master/data")

page %>%
  html_nodes("a") %>%       # find all links
  html_attr("href") %>%     # get the url
  str_subset("\\.csv.zip") -> tmp # find those that end in .csv.zip

tmp[tmp %>%
  basename() %>%
  substr(1,10) %>%
  as.Date() %>% which.max()]

#[1] "/mrc-ide/global-lmic-reports/blob/master/data/2021-05-22_v8.csv.zip"

要获取您可以使用的最新日期的数据 -

tmp %>%
  basename() %>%
  substr(1,10) %>%
  as.Date() %>% max()

#[1] "2021-05-22"