如何检查页面是否包含特定单词。示例:如果页面包含单词“candybar”,我想返回 true 或 false。请注意,“candybar”有时可能位于标签(candybar)之间,有时则不然。我该如何实现这个目标?
这是我“抓取”网站的代码(只是现在不知道如何检查网站):
#!/usr/bin/perl -w
use utf8;
use RPC::XML;
use RPC::XML::Client;
use Data::Dumper;
use Encode;
use Time::HiRes qw(usleep);
print "Content-type:text/html\n\n";
use LWP::Simple;
$pageURL = "http://example.com";
$simplePage=get($pageURL);
if ($simplePage =~ m/candybar/) {
print "its there!";
}
如果您正在查找 HTML 中的单词或以已知方式标记的任何其他内容(例如 XML),我建议您使用某种解析器。我使用 HTML::Tokeparser 但 CPAN 上有很多解析模块。
我已将解析器返回的解释作为注释保留下来,以防您使用此解析器。这是从我用来机器翻译网页文本的实时程序中提取的,因此我删除了一些零碎内容。
上面关于检查LWP返回状态和内容的评论也很明智,如果网站离线了,你需要知道这一点。
打开(我的$fh,“<:utf8", $file ) || die "Can't open $file : $!";
my $p = HTML::TokeParser->new($fh) || die "Can't open: $!";
$p->empty_element_tags(1); # configure its behaviour
# put output into here and it's cumulated
while ( my $token = $p->get_token ) {
#["S", $tag, $attr, $attrseq, $text]
#["E", $tag, $text]
#["T", $text, $is_data]
#["C", $text]
#["D", $text]
#["PI", $token0, $text
my ($type,$string) = get_output($token) ;
# ["T", $text, $is_data] : rule for text
if ( $type eq 'T' && $string =~ /^candybar/ ) {
}