首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于perl HTML解析的一点帮助

关于perl HTML解析的一点帮助
EN

Stack Overflow用户
提问于 2010-07-03 03:17:59
回答 4查看 320关注 0票数 1

我正在开发一个小的perl程序,它将打开一个站点并搜索单词Hail Reports,然后返回给我信息。我对perl非常陌生,因此其中一些问题可能很容易修复。首先,我的代码显示我使用的是一个单一化值。这是我所拥有的

代码语言:javascript
复制
#!/usr/bin/perl -w
use LWP::Simple;

my $html = get("http://www.spc.noaa.gov/climo/reports/last3hours.html")
    or die "Could not fetch NWS page.";
$html =~ m{Hail Reports} || die;
my $hail = $1;
print "$hail\n";

其次,我认为正则表达式是做我想做的事情的最简单的方法,但我不确定我是否能用它们做这件事。我希望我的程序搜索单词Hail Reports,并将Hails Reports和Wind Reports之间的信息返回给我。使用正则表达式可以做到这一点吗?还是应该使用不同的方法?下面是我希望它发回的网页源代码片段

代码语言:javascript
复制
     <tr><th colspan="8">Hail Reports (<a href="last3hours_hail.csv">CSV</a>)&nbsp;(<a href="last3hours_raw_hail.csv">Raw Hail CSV</a>)(<a href="/faq/#6.10">?</a>)</th></tr> 

#The Data here will change throughout the day so normally there will be more info.
      <tr><td colspan="8" class="highlight" align="center">No reports received</td></tr> 
      <tr><th colspan="8">Wind Reports (<a href="last3hours_wind.csv">CSV</a>)&nbsp;(<a href="last3hours_raw_wind.csv">Raw Wind CSV</a>)(<a href="/faq/#6.10">?</a>)</th></tr> 
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-07-03 03:56:45

您在$1中没有捕获到任何内容,因为您的正则表达式都没有包含在括号中。下面的方法对我很有效。

代码语言:javascript
复制
#!/usr/bin/perl
use strict;
use warnings;

use LWP::Simple;

my $html = get("http://www.spc.noaa.gov/climo/reports/last3hours.html")
    or die "Could not fetch NWS page.";

$html =~ m{Hail Reports(.*)Wind Reports}s || die; #Parentheses indicate capture group
my $hail = $1; # $1 contains whatever matched in the (.*) part of above regex
print "$hail\n";
票数 2
EN

Stack Overflow用户

发布于 2010-07-03 04:03:32

未初始化值警告来自$1 --它没有在任何地方定义或设置。

对于行级而不是字节级的"between“,你可以使用:

代码语言:javascript
复制
for (split(/\n/, $html)) {
    print if (/Hail Reports/ .. /Wind Reports/ and !/(?:Hail|Wind) Reports/);
}
票数 3
EN

Stack Overflow用户

发布于 2010-07-03 08:48:15

使用单行和多行匹配。另外,它只会选择文本之间的第一个匹配项,这比贪婪要快一点。

代码语言:javascript
复制
#!/usr/bin/perl -w

use strict;
use LWP::Simple;

   sub main{
      my $html = get("http://www.spc.noaa.gov/climo/reports/last3hours.html")
                 or die "Could not fetch NWS page.";

      # match single and multiple lines + not greedy
      my ($hail, $between, $wind) = $html =~ m/(Hail Reports)(.*?)(Wind Reports)/sm
                 or die "No Hail/Wind Reports";

      print qq{
               Hail:         $hail
               Wind:         $wind
               Between Text: $between
            };
   }

   main();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3168514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档