我的问题是,在R语言中如何下载一个网站上的所有文件?我知道如何逐个下载,但不知道如何一次性全部下载。例如:
我的问题是,在R语言中如何下载一个网站上的所有文件?我知道如何逐个下载,但不知道如何一次性全部下载。例如:
我在页面的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个文件。
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出色的目录创建和文件检查代码嵌入其中。
a[href^='TAB']
做什么?看起来不错。 - Rich ScrivenTAB
开头的href
元素的链接。 - hrbrmstrimport 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)