工作中经常要查看IP地址位于的地址信息,没错,www.ip138.com可以查询到.但是当大批量的查询时,你该怎么办?难道也要一个一个去查询?这种重复性的工作非常耽误时间,不如写个脚本.实现批量查询,脚本和本人博客中的查询手机SIM卡所在省份所使用的方法一样.我也处于刚起步的菜鸟阶段.希望和大家一起学习...
脚本如下:
- #!/usr/bin/perl -w
- use warnings;
- use strict;
- use LWP::UserAgent;
- use HTML::TreeBuilder;
- my $ip_url = 'http://www.ip138.com/ips8.asp?ip=';
- if (@ARGV != 1){
- die "Usage: ./$0 <ip_list> or <ip_addr>..\n";
- }
- foreach (&get_ip_list()) {
- print "$_\t";
- my $link = $ip_url."$_"."&action=2";
- # print "$link\n";
- my $cont = get_html("$link");
- # print "$cont\n";
- my $table = $1 if $cont =~ m{<table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">(.*?)</table>}s;
- $table =~ s/本站主数据://g;
- $table =~ s/参考数据一//g;
- #print "$table\n";
- my $tree = HTML::TreeBuilder->new();
- $tree->strict_comment(1);
- $tree->parse($table);
- $tree->eof();
- my $tr = ($tree->find_by_tag_name('tr'))[2];
- my @kids = $tr->content_list();
- # print "@kids\n"
- if (@kids and ref $kids[0] and $kids[0]->tag() eq 'td'){
- print $kids[0]->as_text( ),"\n";
- }
- $tree->delete;
- sleep(1);
- }
- sub get_html {
- my $browser = LWP::UserAgent->new();
- $browser->agent('Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1; SV1)');
- my $resp = $browser->get(@_);
- return $resp->content;
- }
- sub get_ip_list{
- my @ip_list = ();
- if(!(-r $ARGV[0] and -f _ and -w _)){
- @ip_list = split (/\s/,$ARGV[0]);
- }else{
- open IP,"$ARGV[0]" or die "$ARGV:$!\n";
- while(<IP>){
- chomp;
- $_ =~ s/^\s+//;
- $_ =~ s/\s+$//;
- next if $_ =~ m/^#/;
- next if $_ eq '';
- $_ =~ m/((?:\d+\.){3}\d+)/;
- push (@ip_list,$1);
- }
- }
- return @ip_list;
- }
结果类似于:
总感觉不是很严谨..少点什么东西..望高手指教.