当我们要下载网页的时候,我们常常用到 wget
命令。使用方法是先输入 wget
,后面跟着要下载的文件的 URL。 Wget 会下载给定 URL 中的文件,并将其保存在当前目录中。
wget https://TARGET_URL.com
除了下载 URL 文件外,我平时也会使用 wget
来检查我的博客是否出现故障,过程如下:
wget
目标网页- 查看返回信息
--2022-04-25 19:48:14-- https://blog.haysc.tech/
Resolving blog.haysc.tech (blog.haysc.tech)... 206.189.46.168, ...
Connecting to blog.haysc.tech
(blog.haysc.tech) connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘index.html’
index.html [ <=> ] 30.96K --.-KB/s in 0.1s
2022-04-23 15:43:38 (206 KB/s) - ‘index.html’ saved [21369]
从上面这个演示中,我们能得知网页服务器的网速、解析 IP 以及 HTTP 状态码(e.g. 404、200)这些重要资讯。当我看到 200 OK
时,就知道博客没有崩。
默认状态 wget
目标网页下载到当前目录。而这时候的我只需要查看网页是否异常,并不需要网页内容下载成一个 index.html
的网页文件。
我们有几种方法让 wget
不下载网页到目录。
delete-after
我们可以通过参数 --delete-after
告知 wget
程序在运行后自动删除下载的网页。
wget https://TARGET_URL.com --delete-after
在下面的例子中,得到的网页 index.html
会在程序结束末移除。
wget https://blog.haysc.tech --delete-after
--------------
index.html.tmp [ <=> ] 21.56K 94.9KB/s in 0.2s
2022-04-23 15:43:38 (93.9 KB/s) - ‘index.html.tmp’ saved [21369]
Removing index.html.tmp.
-O-
在 wget
中,我们可以使用 -O
(O 代表输出 Output)把输出写入到指定文件里。而 -O-
则会输出到 stdout
中,即打印在屏幕上 ,而不会储存到某个文件里。
wget https://TARGET_URL.com -O-
在下面的例子中,得到的整个网页 index.html
会以文字的形式输出到屏幕中,类似平时编程中的 print
。
wget https://blog.haysc.tech -O-
--2022-04-23 15:43:38-- https://blog.haysc.tech/
Resolving blog.haysc.tech (blog.haysc.tech)... 2604:a880:2:d0::212a:f001, 138.68.50.15, 138.197.207.178, ...
Connecting to blog.haysc.tech (blog.haysc.tech)|2604:a880:2:d0::212a:f001|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘STDOUT’
- [<=> ] 0 --.-KB/s <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
..........省略后面一大串
–spider
顾名思义,--spider
专门为爬虫使用,用来检查目标文件是否存在、大小。
wget https://TARGET_URL.com --spider
值得注意的是,前面提到的两个方法都会发送 HTTP GET 方法,而 --spider
发送 HTTP HEAD ,只会返回资源的头部信息,而不包含后面的正文。
使用 --spider
时,返回结果为:
Spider mode enabled. Check if remote file exists.
--2022-04-23 15:43:38-- https://blog.haysc.tech/
Resolving blog.haysc.tech (blog.haysc.tech)
Connecting to blog.haysc.tech
(blog.haysc.tech) connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]