아래 코드를 사용하여 공개 PDF 문서를 다운로드하고 개인 파일에 저장합니다. 이 코드는 업로드 한 파일에서 PDF 링크를 가져온 다음 지정된 폴더로 다운로드합니다. 샘플 링크처럼 보일 수 있습니다 :
http://askebsa.dol.gov/BulkFOIARequest/Listings.aspx/GetImage?ack_id=20151008144858P040036764801001&year=2014
URL 문자열에서 추가 텍스트 제거
그것은 다음과 같은 이름을 가진이 PDF 파일에 저장됩니다
GetImage?ack_id=20151008144858P040036764801001&year=2014.pdf
합니다. 20151008144858P040036764801001.pdf
이
이 코드는 다른 고급 코더에 의해 나에게 제공 한 내가 더 이상 얻을 수 있다는 : 만의 고유 ID 번호를 포함하는 것을 볼 수 있도록 다음과 같이
나는 다운로드 이름을 싶습니다 접촉하고, 나는 알아 내기가 힘들다. 이름을 바꾸는 방법.
여러 줄의 코드를 편집 해 보았습니다. 이름을 바꿀 수는 있지만 작동시키지 못한다고 생각합니다. 내가 해봤 조정 :
out_name=str_c(base %>% str_extract("[^/]*.$"), tail, ".pdf")
및
mutate_each(funs(. %>% str_replace("^.*(?=\\?)", "")), link, facsimile_link) %>%
ID 번호. 도움의 R 커뮤니티에 감사드립니다.
# General
# ------------------------------------------------------------------------------
Create <- function(
var_name, # (character) name of the variable to assign to.
expr # (character) the expression to be parsed and evaluated for assignment.
) {
# If a variable `var_name` does not exist then an expression `expr` is
# evaluated and assigned to it.
# If the variable exists, then do nothing:
if(exists(var_name)) {return()}
# Evaluate expression:
parse(text=expr) %>%
eval %>%
# Assign to variable in global environment:
assign(x=var_name, value=., envir=globalenv())
}
# Indices
# ------------------------------------------------------------------------------
AnnualIxUrls <- function(
base_url=ix_base, # (character) base URL
years=annual_ix # (integer) years with annual index files
) {
# Create annual index URLs.
file.path(base_url, "YEARLY_BY_PLAN_YEAR", str_c(years, ".zip"))
}
MonthlyIxUrls <- function(
base_url=ix_base, # (character) base URL
years=monthly_ix # (integer) years with annual index files
) {
# Create annual index URLs.
file.path(base_url, "MONTHLY", years, str_c(years, "-", month.name, ".zip"))
}
IxDown <- function() {
# Download all the index files (as ZIP files).
c(AnnualIxUrls(), MonthlyIxUrls()) %>%
llply(.progress="text", DownFile, di=ix_dir)
}
# Unzip all the index files:
IxUnzip <- . %>% {list.files(ix_dir, ".zip$", full.name=T) %>%
llply(.progress="text", unzip, exdir=ix_dir)}
IxRead <- . %>% # Read all the index files into one data frame
{list.files(ix_dir, ".txt$", full.name=T)} %>%
ldply(.parallel=T, IxLoad) %T>%
# Replace empty strings with NAs:
{.$link[.$link == ""] <- NA} %T>%
{.$facsimile_link[.$facsimile_link == ""] <- NA} %>%
# Remove URL headers from links:
mutate_each(funs(. %>% str_replace("^.*(?=\\?)", "")), link, facsimile_link) %>%
tbl_df
IxLoad <- function(
pat, #(character) input file path
nm=in_colnames #(character) index column names to use
) {
# Loads the index file into a data frame.
fread(pat, data.table=F, sep="|") %>%
setNames(in_colnames) %>%
tbl_df
}
# Images
# ------------------------------------------------------------------------------
Link <- . %$% {str_c(link_base, "?dln=", ack_id, "&year=", filing_year)}
DownLink <- function(
base, #(character)
tail #(character)
) {
if(is.na(tail)) {return(NA)}
DownFile(url=str_c(base, tail), di=pdf_dir,
out_name=str_c(base %>% str_extract("[^/]*.$"), tail, ".pdf")
)
}
DlRow <- . %$% {
DownLink(link_base, link)
DownLink(facs_base, facsimile_link)
TRUE
}
DlRows <- . %>% adply(.margins=1, .fun=DlRow, .progress="text")
# General
# ------------------------------------------------------------------------------
DownFile <- function(
url, # (character)
di, # (character) output directory.
out_name=NA # (character) output file name.
) {
# Downloads and saves a file from the DOL site.
if(is.na(out_name)) {out_name <- str_extract(url, "[^/]*$")}
# Set up a CURL handle:
curl <- getCurlHandle()
# Add options to CURL handle (cookie and to follow redirects):
curlSetOpt(
cookiefile=file.path(in_dir, cookie_file),
curl=curl,
followLocation=T
)
# Download the binary data:
getBinaryURL(url,curl=curl) %>%
# Save the binary data:
writeBin(file.path(di, str_c(out_name, ".pdf")))
}
ProcessIndex <- function(
i=LoadIndex() #(data frame) the data loaded from index file
) {
# Processes the index: downloads each of the documents listed in the file.
# Define a functional sequence to apply to every entry:
{. %$% {
# Dowload the "link" variable if defined:
if(!is.na(link) & str_length(link)) {
DownFile(url=link, dest_file=str_c(ack_id, ".pdf"))
}
# Dowload the "facsimile_link" variable if defined:
if(!is.na(facsimile_link) & str_length(facsimile_link)) {
DownFile(url=facsimile_link, dest_file=str_c(ack_id, "_facs.pdf"))
}
TRUE
}} %>%
# Apply this functional sequence to each row in the index data frame:
adply(.data=i,.progress="text", .fun=., .margins=1)
}
# Sample
# ------------------------------------------------------------------------------
# Download all the sample files.
SampleDown <- . %$% LINK %>% llply(.progress="text", DownFile, sample_dir)
완벽하게 작동하므로 고맙습니다. @ zelite !!!!! – richiepop2