使用wget命令来下载API和网站

本文介绍如何利用wget命令行工具进行API文档的下载。详细解释了wget的各种参数用法,如递归下载(-r)、转换链接(-k)、获取网页元素(-p)等,并提供了具体的使用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有很多项目中的API都是在线阅读的并没有统一的下载文件,各种各样的API文档也是要看个人的阅读习惯,也有的更新并不同步的可能,我个人习惯直接在firefox中直接查看,所以就习惯了使用wget来下载这些API。

wget  linux下最经典的下载命令,在命令行中输入wget --help就显示出如下帮助参数。乍看之下,好多的参数已经让人有点头晕了(毕竟是个超强大的命令^_^),当然,我不需要用到这么多参数。

其实需要只需在终端下输入:
wget -r -p -k -np http://your need get web address 例如:wget -r -p -k -np http://www.jdom.org/docs/我需要下载jdom的文档,只需要输入需要下载的网络地址就可以了。

-r 表示递归下载,会下所有的链接,不过注意的是,不能单独使用整个参数,除非的的硬盘能够装下整个internet(可能性好小阿^_^),所以需要加上-np 这个参数表示不下载别的站点的链接。
-k 表示将下载的网页里的链接修改为本地链接
-p 获取所显示网页的所有元素,比如图片什么的,还有css文件哦,还可以拿来借鉴阿。

其他常用的参数:
-c 表示断点续传
-t 100 表示重试100次, -t 0 表示无穷次重试
-i file 可以将要下载的url写到一个文件中,每个url一行
--reject=avi,rmvb 表示不下载avi,rmvb的文件
--accept=jpg,jpeg, 表示下载jpg,jpeg的文件
在用户目录下建立.wgetrc的文件,里面写上 http-proxy=123.123.123.123:80, 然后在加上参数 --proxy=on
如果需要密码,在加上-proxy-user=username, --proxy-passwd=pwssword,这样就可以下载小电影了^_^



GNU Wget 1.10.2, a non-interactive network retriever.
Usage: wget [OPTION]... [URL]...

Mandatory arguments to long options are mandatory for short options too.

Startup:
  -V,  --version           display the version of Wget and exit.
  -h,  --help              print this help.
  -b,  --background        go to background after startup.
  -e,  --execute=COMMAND   execute a `.wgetrc'-style command.

Logging and input file:
  -o,  --output-file=FILE    log messages to FILE.
  -a,  --append-output=FILE  append messages to FILE.
  -d,  --debug               print lots of debugging information.
  -q,  --quiet               quiet (no output).
  -v,  --verbose             be verbose (this is the default).
  -nv, --no-verbose          turn off verboseness, without being quiet.
  -i,  --input-file=FILE     download URLs found in FILE.
  -F,  --force-html          treat input file as HTML.
  -B,  --base=URL            prepends URL to relative links in -F -i file.

Download:
  -t,  --tries=NUMBER            set number of retries to NUMBER (0 unlimits).
       --retry-connrefused       retry even if connection is refused.
  -O,  --output-document=FILE    write documents to FILE.
  -nc, --no-clobber              skip downloads that would download to
                                 existing files.
  -c,  --continue                resume getting a partially-downloaded file.
       --progress=TYPE           select progress gauge type.
  -N,  --timestamping            don't re-retrieve files unless newer than
                                 local.
  -S,  --server-response         print server response.
       --spider                  don't download anything.
  -T,  --timeout=SECONDS         set all timeout values to SECONDS.
       --dns-timeout=SECS        set the DNS lookup timeout to SECS.
       --connect-timeout=SECS    set the connect timeout to SECS.
       --read-timeout=SECS       set the read timeout to SECS.
  -w,  --wait=SECONDS            wait SECONDS between retrievals.
       --waitretry=SECONDS       wait 1..SECONDS between retries of a retrieval.
       --random-wait             wait from 0...2*WAIT secs between retrievals.
  -Y,  --proxy                   explicitly turn on proxy.
       --no-proxy                explicitly turn off proxy.
  -Q,  --quota=NUMBER            set retrieval quota to NUMBER.
       --bind-address=ADDRESS    bind to ADDRESS (hostname or IP) on local host.
       --limit-rate=RATE         limit download rate to RATE.
       --no-dns-cache            disable caching DNS lookups.
       --restrict-file-names=OS  restrict chars in file names to ones OS allows.
  -4,  --inet4-only              connect only to IPv4 addresses.
  -6,  --inet6-only              connect only to IPv6 addresses.
       --prefer-family=FAMILY    connect first to addresses of specified family,
                                 one of IPv6, IPv4, or none.
       --user=USER               set both ftp and http user to USER.
       --password=PASS           set both ftp and http password to PASS.

Directories:
  -nd, --no-directories           don't create directories.
  -x,  --force-directories        force creation of directories.
  -nH, --no-host-directories      don't create host directories.
       --protocol-directories     use protocol name in directories.
  -P,  --directory-prefix=PREFIX  save files to PREFIX/...
       --cut-dirs=NUMBER          ignore NUMBER remote directory components.

HTTP options:
       --http-user=USER        set http user to USER.
       --http-password=PASS    set http password to PASS.
       --no-cache              disallow server-cached data.
  -E,  --html-extension        save HTML documents with `.html' extension.
       --ignore-length         ignore `Content-Length' header field.
       --header=STRING         insert STRING among the headers.
       --proxy-user=USER       set USER as proxy username.
       --proxy-password=PASS   set PASS as proxy password.
       --referer=URL           include `Referer: URL' header in HTTP request.
       --save-headers          save the HTTP headers to file.
  -U,  --user-agent=AGENT      identify as AGENT instead of Wget/VERSION.
       --no-http-keep-alive    disable HTTP keep-alive (persistent connections).
       --no-cookies            don't use cookies.
       --load-cookies=FILE     load cookies from FILE before session.
       --save-cookies=FILE     save cookies to FILE after session.
       --keep-session-cookies  load and save session (non-permanent) cookies.
       --post-data=STRING      use the POST method; send STRING as the data.
       --post-file=FILE        use the POST method; send contents of FILE.

HTTPS (SSL/TLS) options:
       --secure-protocol=PR     choose secure protocol, one of auto, SSLv2,
                                SSLv3, and TLSv1.
       --no-check-certificate   don't validate the server's certificate.
       --certificate=FILE       client certificate file.
       --certificate-type=TYPE  client certificate type, PEM or DER.
       --private-key=FILE       private key file.
       --private-key-type=TYPE  private key type, PEM or DER.
       --ca-certificate=FILE    file with the bundle of CA's.
       --ca-directory=DIR       directory where hash list of CA's is stored.
       --random-file=FILE       file with random data for seeding the SSL PRNG.
       --egd-file=FILE          file naming the EGD socket with random data.

FTP options:
       --ftp-user=USER         set ftp user to USER.
       --ftp-password=PASS     set ftp password to PASS.
       --no-remove-listing     don't remove `.listing' files.
       --no-glob               turn off FTP file name globbing.
       --no-passive-ftp        disable the "passive" transfer mode.
       --retr-symlinks         when recursing, get linked-to files (not dir).
       --preserve-permissions  preserve remote file permissions.

Recursive download:
  -r,  --recursive          specify recursive download.
  -l,  --level=NUMBER       maximum recursion depth (inf or 0 for infinite).
       --delete-after       delete files locally after downloading them.
  -k,  --convert-links      make links in downloaded HTML point to local files.
  -K,  --backup-converted   before converting file X, back up as X.orig.
  -m,  --mirror             shortcut for -N -r -l inf --no-remove-listing.
  -p,  --page-requisites    get all images, etc. needed to display HTML page.
       --strict-comments    turn on strict (SGML) handling of HTML comments.

Recursive accept/reject:
  -A,  --accept=LIST               comma-separated list of accepted extensions.
  -R,  --reject=LIST               comma-separated list of rejected extensions.
  -D,  --domains=LIST              comma-separated list of accepted domains.
       --exclude-domains=LIST      comma-separated list of rejected domains.
       --follow-ftp                follow FTP links from HTML documents.
       --follow-tags=LIST          comma-separated list of followed HTML tags.
       --ignore-tags=LIST          comma-separated list of ignored HTML tags.
  -H,  --span-hosts                go to foreign hosts when recursive.
  -L,  --relative                  follow relative links only.
  -I,  --include-directories=LIST  list of allowed directories.
  -X,  --exclude-directories=LIST  list of excluded directories.
  -np, --no-parent                 don't ascend to the parent directory.

<think>好的,用户现在想了解curlwget命令使用。之前我们讨论过TCP协议相关的术语,用户可能是在学习网络相关的知识,现在想进一步掌握实际应用中的工具。 首先,我需要确定用户的使用场景。用户可能是运维人员、开发者,或者刚开始学习Linux的人。他们可能需要用这些工具下载文件、测试API,或者自动化脚本。考虑到之前的问题涉及SYN、ACK等底层协议,用户可能对网络通信有基础了解,但需要更实用的工具指导。 接下来,用户的需求是什么?他们可能想知道这两个命令的基本用法、常见选项以及区别。深层需求可能包括如何选择适合的工具,解决下载中的问题,或者集成到脚本中。需要比较curlwget,帮助用户根据场景选择。 用户可能存在的疑问包括:curlwget有什么区别?什么时候用哪个?如何处理下载中断、认证、代理等问题?可能需要举例说明常见的使用场景,比如下载文件、发送POST请求、限速下载、递归下载整个网站等。 我需要整理curlwget的主要功能、常用选项、典型用例,并对比它们的优缺点。还要注意给出实际例子,让用户更容易理解。例如,使用curl发送带JSON头的POST请求,或者用wget递归下载网站镜像。 另外,用户可能遇到证书问题、重定向、断点续传等情况,需要涵盖这些方面的选项。比如curl的-k选项忽略证书错误,wget的-c选项继续下载。同时,提供一些高级技巧,比如用curl测试API响应时间,或者用wget限速避免占用过多带宽。 还要注意安全性问题,比如在使用curl传递密码时用-u还是更安全的方式,避免在历史记录中留下敏感信息。可能提到使用环境变量或者配置文件来管理凭证。 最后,总结两者的适用场景,帮助用户根据需求选择合适的工具。例如,curl更适合API交互灵活请求,而wget适合下载文件网站镜像。</think>以下是对`curl``wget`命令的详细对比及使用指南,包含实际场景示例运维技巧: --- ### **一、核心定位对比** | 特性 | curl | wget | |---------------|-------------------------------------|-----------------------------------| | **协议支持** | 支持HTTP/HTTPS/FTP/SCP/SMTP等23+协议 | 主要专注HTTP/HTTPS/FTP/FTPS | | **交互模式** | 更适合API调试、请求构造 | 专为文件下载优化 | | **持久性** | 默认输出到stdout | 自动保存到文件 | | **递归下载** | 不支持 | 支持目录递归下载 | | **开发语言** | C语言编写 | C++编写 | --- ### **二、curl核心用法** #### 1. 基础请求 ```bash # 发送GET请求并显示响应头 $ curl -I https://www.example.com # 下载文件并指定保存名称 $ curl -o image.jpg http://example.com/pic.jpg # 发送POST请求(JSON格式) $ curl -X POST -H "Content-Type: application/json" -d '{"user":"admin"}' http://api.example.com/login ``` #### 2. 认证相关 ```bash # Basic认证 $ curl -u username:password http://protected.example.com # Bearer Token认证 $ curl -H "Authorization: Bearer <token>" http://api.example.com/data ``` #### 3. 调试与监控 ```bash # 显示详细通信过程(调试用) $ curl -v https://www.example.com # 测试响应时间(单位:秒) $ curl -w "DNS: %{time_namelookup} Connect: %{time_connect} Total: %{time_total}\n" -o /dev/null -s https://example.com ``` #### 4. 高级功能 ```bash # 断点续传(适合大文件) $ curl -C - -O http://example.com/large_file.zip # 限速下载(100KB/s) $ curl --limit-rate 100K -O http://example.com/file.iso # 代理设置 $ curl -x http://proxy.example.com:8080 http://external-site.com ``` --- ### **三、wget核心用法** #### 1. 下载操作 ```bash # 下载单个文件 $ wget http://example.com/file.zip # 后台下载(适合长时间任务) $ wget -bqc http://example.com/large_video.mp4 # 断点续传 $ wget -c http://example.com/interrupted_download.iso ``` #### 2. 批量下载 ```bash # 下载文件列表(每行一个URL) $ wget -i url_list.txt # 镜像整个网站(谨慎使用!) $ wget --mirror --convert-links --page-requisites --no-parent http://example.com/subdir/ ``` #### 3. 限速与重试 ```bash # 限速500KB/s(防止带宽占满) $ wget --limit-rate=500k http://example.com/ubuntu.iso # 失败重试(最多5次) $ wget -t5 http://unstable-site.com/file ``` #### 4. 认证与SSL ```bash # FTP下载(带认证) $ wget --ftp-user=user --ftp-password=pass ftp://example.com/file # 忽略SSL证书验证(测试环境用) $ wget --no-check-certificate https://self-signed.example.com ``` --- ### **四、运维场景对比选择** | **使用场景** | **推荐工具** | **示例命令** | |----------------------------|-------------|-------------| | API接口测试/调试 | curl | `curl -X PUT -d '{"status":1}' http://api.example.com/resource` | | 大文件下载(需断点续传) | wget | `wget -c http://mirror.example.com/centos.iso` | | 网页资源批量抓取 | wget | `wget -r -np -R "index.html*" http://docs.example.com` | | 需要查看详细HTTP头的请求 | curl | `curl -I -X HEAD http://example.com/login` | | 需要模拟浏览器行为的下载 | curl | `curl -A "Mozilla/5.0" --cookie "session=abc123" http://example.com` | | 创建网站本地镜像 | wget | `wget --mirror --convert-links http://example.com` | --- ### **五、高级技巧** #### 1. 结合管道处理 ```bash # 下载JSON数据并用jq解析 $ curl -s http://api.example.com/data | jq '.results[].name' # 下载CSV文件实时处理 $ wget -qO- http://reports.example.com/sales.csv | awk -F, '{sum+=$3} END{print sum}' ``` #### 2. 证书问题处理 ```bash # 指定客户端证书(双向SSL认证) $ curl --cert client.pem --key key.pem https://secure-api.example.com # 信任自定义CA证书 $ wget --ca-certificate=my-ca.pem https://internal.example.com ``` #### 3. 防火墙穿透 ```bash # 通过SOCKS代理 $ curl -x socks5://user:pass@proxy.example.com:1080 http://blocked-site.com # 使用被动模式FTP(穿透防火墙) $ wget --passive-ftp ftp://files.example.com/reports/ ``` --- ### **六、常见错误处理** | **错误现象** | **解决方案** | |---------------------------|----------------------------------------| | `SSL certificate problem` | 添加`--insecure`(curl)或`--no-check-certificate`(wget) | | `Connection refused` | 检查目标端口是否开放,确认防火墙规则 | | `403 Forbidden` | 添加用户代理:`-A "Mozilla/5.0"` | | 下载文件不完整 | 使用`-C -`(curl)或`-c`(wget)恢复下载 | | 递归下载陷入死循环 | 设置`--level=N`限制递归深度 | --- ### **七、性能优化参数** ```bash # curl并行下载(多线程效果) $ curl -Z -O http://cdn.example.com/file.part1 -O http://cdn.example.com/file.part2 # wget多镜像源加速 $ wget --prefer-family=IPv4 --dns-timeout=5 --connect-timeout=5 http://mirror{1,2}.example.com/package.deb ``` 掌握这些用法后,可以通过组合命令实现复杂需求,例如: ```bash # 下载最新版软件包并自动校验(wget + shasum) $ wget $(curl -s https://api.github.com/repos/project/releases/latest | jq -r '.assets[].browser_download_url') && sha256sum -c checksum.txt ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值