2017-03-04 12 views
-3

以下のコードを使用して、公開されているPDFドキュメントをダウンロードし、個人用ファイルに保存しています。このコードは、アップロードしたファイルからPDFリンクを取り出し、指定されたフォルダにダウンロードします。サンプルリンクは次のようになります。
http://askebsa.dol.gov/BulkFOIARequest/Listings.aspx/GetImage?ack_id=20151008144858P040036764801001&year=2014URL文字列から余分なテキストを削除してください

、それは、次の名前を持つこのPDFファイルを保存します:

GetImage?ack_id=20151008144858P040036764801001&year=2014.pdfを。

次のようになりますように私は、唯一の固有のID番号を含めるには、ダウンロードの名を欲しい:20151008144858P040036764801001.pdf

このコードは、私はもはや得ることができないこと、他のより高度なコーダによって私に提供されました連絡先には、名前を変更する方法を把握するのに苦労しています。

私はここでいくつかの行のコードを編集しようとしましたが、名前を変更しても機能するようにはできませんでした。私は調整を試してみた:

out_name=str_c(base %>% str_extract("[^/]*.$"), tail, ".pdf")

mutate_each(funs(. %>% str_replace("^.*(?=\\?)", "")), link, facsimile_link) %>%

私はより高度な誰かが私はちょうどpdfドキュメントを保存することができるように、右のコードを見つけて挿入することができるかもしれない期待していました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) 

答えて

3

元のコードでは、正規表現を使用してURL文字列の特定の部分を抽出しています。次のように文字列置換を使用することをお勧めします。

out_name <- str_replace(url, "^.*ack_id=(.*)&.*$", "\\1")

我々は、すべての文字列に一致し、id=&間のキャプチャグループ(parentesis間のもの)を作成しています。 str_replaceの最後の引数は、文字列の代わりに使用するものです。 "\\1"は、最初のキャプチャグループを使用することを意味します。これは、pdf名に使用するIDです。

+0

これは完璧に動作します、ありがとうございます@ゼリット!!!!! – richiepop2

関連する問題