【问题标题】:How to use R to identify most up-to-date downloadable file on a web page?如何使用 R 识别网页上最新的可下载文件?
【发布时间】:2021-08-20 04:23:22
【问题描述】:

我正在尝试定期检查添加到页面 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-05-22_v8.csv.zip 截至 2021-06-01 检查。

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

【问题讨论】:

    标签: r download scrape


    【解决方案1】:

    您可以将链接转换为日期并使用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"
    

    【讨论】:

    • 谢谢!此代码完美返回最新 .csv.zip 文件的 URL。虽然是一项微不足道的任务,但需要的是最新 .csv.zip 文件的 日期,即本例中的 2021-05-22 字符串。
    • 查看更新的答案以获取最新的 .csv.zip 文件的日期
    • 这会返回准确的想要的,即最新文件的日期。高超。再次感谢。案件已解决。
    猜你喜欢
    • 2017-06-25
    • 2015-10-11
    • 2020-10-17
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2021-12-19
    相关资源
    最近更新 更多