【问题标题】:Retrieve date modified of a file from an FTP Server从 FTP 服务器检索文件的修改日期
【发布时间】:2020-04-22 15:34:21
【问题描述】:

基于这个问题 (Retrieve modified DateTime of a file from an FTP Server),很清楚如何获取日期修改值。但是,即使从 FTP 站点可以看到完整日期,也不会返回完整日期。

这显示了如何获取 ftp://ftp.FreeBSD.org/pub/FreeBSD/ 处文件的日期修改值

library(curl)
library(stringr)

con <- curl("ftp://ftp.FreeBSD.org/pub/FreeBSD/")
dat <- readLines(con)
close(con)

no_dirs <- grep("^d", dat, value=TRUE, invert=TRUE)
date_and_name <- sub("^[[:alnum:][:punct:][:blank:]]{43}", "", no_dirs)
dates <- sub('\\s[[:alpha:][:punct:][:alpha:]]+$', '', date_and_name)
dates
## [1]  "May 07  2015" "Apr 22 15:15" "Apr 22 10:00"

有些日期采用月/日/年格式,其他日期采用月/日/小时/分钟格式。

查看 FTP 站点,所有日期均采用月/日/年时/分/秒格式。

我认为这与 Unix 格式标准有关(在 FTP details command doesn't seem to return the year the file was modified, is there a way around this? 中解释)。最好能得到完整的日期。

【问题讨论】:

    标签: r web-scraping ftp


    【解决方案1】:

    如果您使用download.file,您将获得目录的 html 表示,您可以使用 xml2 包对其进行解析。

    read_ftp <- function(url)
    {
      tmp <- tempfile()
      download.file(url, tmp, quiet = TRUE)
      html <- xml2::read_html(readChar(tmp, 1e6))
      file.remove(tmp)
      lines <- strsplit(xml2::xml_text(html), "[\n\r]+")[[1]]
      lines <- grep("(\\d{2}/){2}\\d{4}", lines, value = TRUE) 
      result <- read.table(text = lines, stringsAsFactors = FALSE)
      setNames(result, c("Date", "Time", "Size", "File"))    
    }
    

    这允许您这样做:

    read_ftp("ftp://ftp.FreeBSD.org/pub/FreeBSD/")
    #>         Date    Time      Size        File
    #> 1 05/07/2015 12:00AM     4,259  README.TXT
    #> 2 04/22/2020 08:00PM        35   TIMESTAMP
    #> 3 04/22/2020 08:00PM Directory development
    #> 4 04/22/2020 10:00AM     2,325   dir.sizes
    #> 5 11/12/2017 12:00AM Directory         doc
    #> 6 11/12/2017 12:00AM Directory       ports
    #> 7 04/22/2020 08:00PM Directory    releases
    #> 8 11/09/2018 12:00AM Directory   snapshots
    

    reprex package (v0.3.0) 于 2020 年 4 月 22 日创建

    【讨论】:

    • @fawda123 抱歉 - 请查看我的更新答案,现在应该给出正确的结果。
    • 刚刚发现这在 Unix 环境下不起作用。通常这不会是一个问题,但我在 Windows 之外运行失败的测试。
    • @fawda123 我无法在 unix 设置上进行测试。你在download.file保存的文件中得到了什么内容?还是您从服务器收到错误消息?
    • 内容下载正常,但日期格式与我原帖中的相同。
    • @fawda123 是的,这个函数解析的响应似乎只有在使用winInet的情况下才会被传递。我可以尝试挖掘 curl 文档,看看是否可以说服服务器通过 libcurl 返回该响应。同时,您能否检查一下您在download.file 中使用method = "wget" 得到的响应类型 - 我认为您的 unix 系统将提供此功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多