从网站下载文件夹中的所有文件

7
3个回答

13

我在页面的56个文件中测试了一个小子集(3个),它可以正常工作。

## your base url
url <- "http://www2.census.gov/geo/docs/maps-data/data/rel/t00t10/"
## query the url to get all the file names ending in '.zip'
zips <- XML::getHTMLLinks(
    url, 
    xpQuery = "//a/@href['.zip'=substring(., string-length(.) - 3)]"
)
## create a new directory 'myzips' to hold the downloads
dir.create("myzips")
## save the current directory path for later
wd <- getwd()
## change working directory for the download
setwd("myzips")
## create all the new files
file.create(zips)
## download them all
lapply(paste0(url, zips), function(x) download.file(x, basename(x)))
## reset working directory to original
setwd(wd)

现在所有的zip文件都在目录 myzips 中,已准备好进行进一步的处理。作为 lapply() 的替代方案,您还可以使用 for() 循环。

## download them all
for(u in paste0(url, zips)) download.file(u, basename(u))

当然,设置quiet = TRUE可能很好,因为我们要下载56个文件。


1
这个很好用。然而,在我使用它的一个网站上,“zips”包含了zip文件的完整路径。因此,在“lapply”函数中,“paste0(url,zips)”是不必要的,“zips”就足够了。感谢@Dirty Sock Sniffer。 - Clay
1
@Rich 有没有不覆盖文件的方法? - x1carbon
@Rich Scriven 谢谢您的回复,但是 "xpQuery = "//a/@href['.txt'=substring(., string-length(.) - 3)]" 的意思是什么?我该如何将其更改为文本文件? - minoo

9
稍微有些不同的方法。
library(rvest)
library(httr)
library(pbapply)
library(stringi)

URL <- "http://www2.census.gov/geo/docs/maps-data/data/rel/t00t10/"

pg <- read_html(URL)
zips <- grep("zip$", html_attr(html_nodes(pg, "a[href^='TAB']"), "href"), value=TRUE)

invisible(pbsapply(zips, function(zip_file) {
  GET(URL %s+% zip_file, write_disk(zip_file))
}))

通过此功能,您可以获得进度条和内置的“缓存”(write_disk不会覆盖已经下载的文件)。

您还可以将Richard出色的目录创建和文件检查代码嵌入其中。


1
a[href^='TAB'] 做什么?看起来不错。 - Rich Scriven
1
它选择所有具有以TAB开头的href元素的链接。 - hrbrmstr
1
太好了,我知道了!我一直在尝试使用links[grep("TAB2000", links)]来对href属性列表进行子集化,但是使用grep感觉非常不直观。 - Sarah Hailey
@hrbrmstr感谢您的回复,但"a[href^='TAB']"的意思是什么,我该如何将其更改为下载文本文件? - minoo

0
如果您能够使用Python 3,我刚刚成功地让这段代码在类似的人口普查网站上运行。虽然我不得不硬编码所有州的代码,但它确实能够完成工作。
import wget
root_url = 'https://www2.census.gov/geo/docs/maps-data/data/rel/t00t10/TAB2000_TAB2010_ST_'
states = [str(st) for st in ["01","02","04","05", "06", "08", "09","10", 
                         "11", "12", "13", "15", "16", "17", "18", 
                         "19", "20", "21", "22", "23", "24", "25", "26", 
                         "27", "28", "29", "30", "31", "32", "33","34",
                        "35","36", "37", "38", "39", "40", "41", "42",
                        "44", "45","46", "47", "48", "49", "50", "51",
                        "53", "54", "55", "56", "72"]]
ext = '_v2.zip'
for state in states:
    print("downloading state number " + state)
    fname = state + ext
    wget.download(root_url + fname)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接