我是编程新手,也在学习 perl。
这是我的问题:如何在网页中搜索字符串并打印存在搜索字符串的整行?
是否可以直接找到/点击该字符串,然后打印存在搜索字符串的整行?我们需要为此强制使用 xpaths 吗?
我是编程新手,也在学习 perl。
这是我的问题:如何在网页中搜索字符串并打印存在搜索字符串的整行?
是否可以直接找到/点击该字符串,然后打印存在搜索字符串的整行?我们需要为此强制使用 xpaths 吗?
如果它只是您正在寻找的一个非常基本的字符串,您可以使用LWP::Simple和一个像这样的小正则表达式:
use LWP::Simple;
my $doc = get('http://stackoverflow.com/q/11771655/479133') || die "GET failed";
foreach my $line (split("\n", $doc)) {
print $line and last if $line =~ m/Here's my query/;
}
CPAN 上有无数的模块可以做这些事情。如果您需要“更大”的东西,请查看Task::Kensho::WebCrawling 。
LWP::UserAgent
并且HTML::Parser
可以使用:
#!/usr/bin/env perl
use strict;
use warnings;
use HTML::Parser;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $response = $ua->get('http://search.cpan.org/');
if ( !$response->is_success ) {
print "No matches\n";
exit 1;
}
my $parser = HTML::Parser->new( 'text_h' => [ \&text_handler, 'dtext' ] );
$parser->parse( $response->decoded_content );
sub text_handler {
chomp( my $text = shift );
if ( $text =~ /language/i ) {
print "Matched: $text\n";
}
}