【问题标题】:How to search a string in web page and print that full line in which search string is present?如何在网页中搜索字符串并打印存在搜索字符串的整行?
【发布时间】:2014-09-13 06:54:11
【问题描述】:

我是编程新手,也在学习 perl。

这是我的问题:如何在网页中搜索字符串并打印存在搜索字符串的整行?

是否可以直接查找/点击该字符串,然后打印存在搜索字符串的整行?我们是否需要为此强制使用 xpath?

【问题讨论】:

    标签: perl


    【解决方案1】:

    如果您要查找的只是一个非常基本的字符串,您可以使用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

    【讨论】:

      【解决方案2】:

      LWP::UserAgentHTML::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";
          }
      }
      

      【讨论】:

      • 你可能过于复杂了。虽然您通常肯定会使用 HTML 解析器来处理 HTML,但在这种情况下,问题要求“存在搜索字符串的完整行”。在这种情况下,正确的答案是在换行符上拆分输入并搜索各个行。
      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2016-01-11
      • 2016-11-30
      相关资源
      最近更新 更多