另一个费力的标题...不好意思。。。无论如何,我有一个名为mash.txt
的文件,其中包含一堆这样的URL:
http://www...
http://www...
http://www...
.
.
.
所以,在这一点上,我想将这些(URL)输入到一个数组中——可能不必在此过程中声明任何内容——然后递归地从每个文件中吸收 HTML 数据并将其全部附加到同一个文件中——我想必须创建......无论如何,提前感谢。
实际上,为了完全坦率,根据设计,我想将每个 HTML 标签中 option
标签下的值( value
)与此文档匹配,所以我没有那么多垃圾......也就是说,这些中的每一个
http://www...
会产生这样的东西
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
DATA!
</TITLE>
</HEAD>
<BODY>
.
.
.
我想要的所有这些只是option
标签下的value
名称,该标签出现在此mash.txt
的每个 HTML 中。
下面获取 mash.txt 中每个 URL 的 HTML 内容,检索所有选项中的所有值,并将它们推送到单个数组中。然后将生成的数组传递给input.template,并将处理后的输出写入output.html:
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use HTML::TreeBuilder;
use Template;
my %values;
my $input_file = 'mash.txt';
my $input_template = 'input.template';
my $output_file = 'output.html';
# create a new lwp user agent object (our browser).
my $ua = LWP::UserAgent->new( );
# open the input file (mash.txt) for reading.
open my $fh, '<', $input_file or die "cannot open '$input_file': $!";
# iterate through each line (url) in the input file.
while ( my $url = <$fh> )
{
# get the html contents from url. It returns a handy response object.
my $response = $ua->get( $url );
# if we successfully got the html contents from url.
if ( $response->is_success )
{
# create a new html tree builder object (our html parser) from the html content.
my $tb = HTML::TreeBuilder->new_from_content( $response->decoded_content );
# fetch values across options and push them into the values array.
# look_down returns an array of option node objects, which we translate to the value of the value attribute via attr upon map.
$values{$_} = undef for ( map { $_->attr( 'value' ) } $tb->look_down( _tag => 'option' ) );
}
# else we failed to get the html contents from url.
else
{
# warn of failure before next iteration (next url).
warn "could not get '$url': " . $response->status_line;
}
}
# close the input file since we have finished with it.
close $fh;
# create a new template object (our output processor).
my $tp = Template->new( ) || die Template->error( );
# process the input template (input.template), passing in the values array, and write the result to the output file (output.html).
$tp->process( $input_template, { values => [ keys %values ] }, $output_file ) || die $tp->error( );
__END__
input.template可能看起来像这样:
<ul>
[% FOREACH value IN values %]
<li>[% value %]</li>
[% END %]
</ul>