求助:在R中使用download.file的wget方法及配置额外参数
Alright, let's work through your R + wget problem together—there are a couple of quick fixes needed for your code, plus a straightforward way to save all files to a target folder.
1. Fix the extra Parameter Mistakes
Your current code uses getOption() for the extra argument, which is incorrect—getOption() is meant to retrieve R's internal settings, not pass command-line arguments to wget. Also, you have a typo in the --random wait parameter: wget expects it as a single hyphenated argument --random-wait.
Instead, pass your wget options as a character vector (each option as a separate string) or a single space-separated string.
2. Correct Code to Download a Full Local Copy
If you want a fully functional local copy of the page (with all linked resources like images, CSS, and working local links), you'll want to add the -k option to wget—it converts absolute links to relative ones so the local page loads properly.
First, create a target folder (to keep everything organized):
# Create a folder if it doesn't exist dir.create("wikipedia_local", recursive = TRUE, showWarnings = FALSE)
Then use this corrected download.file() call:
download.file( url = "https://www.wikipedia.org/", destfile = "wikipedia_local/index.html", # Save the main page to the folder method = "wget", extra = c("--random-wait", "-p", "-k", "-P", "wikipedia_local") )
Let's break down the wget options here:
--random-wait: Adds random delays between requests to avoid overwhelming the server-p: Downloads all resources required to display the page (images, stylesheets, scripts)-k: Converts absolute URLs in the page to relative paths, so your local copy loads all resources correctly-P wikipedia_local: Saves all downloaded resources (like images/CSS) directly into your target folder
3. Saving to a Specific Folder
As shown above, combining dir.create() (to ensure the folder exists) with wget's -P option is the cleanest way to direct all files to a folder. The destfile points to the main HTML file inside that folder, so wget knows where to place the core page and uses the -P path for supporting assets.
Quick Troubleshooting Tip
Make sure wget is installed on your system and accessible to R. You can check this by running:
Sys.which("wget")
If this returns an empty string, you'll need to install wget (e.g., via Homebrew on macOS, Chocolatey on Windows, or your Linux package manager) and ensure its path is added to your system's environment variables.
内容的提问来源于stack exchange,提问作者Carolin

