26.6 抓網頁程式

以下這支程式很像 wget,可用來抓取指定的網頁檔案。

#! /usr/bin/perl

use strict;

# 使用 IO::Socket 模組
use IO::Socket;

# 取得命令列中的網頁位址,放入 $url 中
my $url=shift || die "您沒有輸入 url 網址!\n";

# 比對網頁位址是否合乎格式?
my ($host, $file) = $url =~ m!http://([^/]+)(/[^\#]*)!;  #(註1)

# 若比對正確,才抓取
if ($host) {

	# 產生一個 IO::Socket::INET 物件
	my $socket = IO::Socket::INET->new(
		PeerAddr => $host,			# 指定主機位址
		PeerPort => 'http(80)'		# 指定 port 號
	);

	# 針對 $socket 寫入,此動作形同對 $host 主機提出網頁檔 $file 的要求
	print $socket "GET $file HTTP/1.0\n\n";

	# 只要由 $socket 讀到一列資料,就處理之
	while(my $line=<$socket>) {

		# 把 CR (^M) 換掉
		$line =~ s/\r//g;

		# 顯示該列內容 (註2)
		print $line;

	}

}

使用法:

1. 存成 wget.pl

2. chmod +x wget.pl

3. ./wget.pl http://linux.tnc.edu.tw/techdoc/FSF.htm > FSF.htm

註1:取自 Network Programming with Perl, 119 頁. Lincoln D.Stein. Addison Wesley. 2001

註2:本程式連 Web server 送給 client 端的表頭訊息,都會顯示出來。比如:


HTTP/1.1 200 OK
Date: Thu, 2 Aug 2003 23:55:46 GMT
Server: Apache/1.3.26 (Unix) PHP/4.1.2
Last-Modified: Tue, 2 Apr 2002 06:13:58 GMT
ETag: "9d821-5dac-3cc4fba6"
Accept-Ranges: bytes
Content-Length: 23980
Connection: close
Content-Type: text/html

註3:這裡有 IO::Socket::INET 的 說明文件,可執行 perldoc IO::Socket::INET 取得。