【问题标题】:How can I extract HTML img tags wrapped in anchors in Perl?如何在 Perl 中提取包装在锚点中的 HTML img 标签?
【发布时间】:2010-12-31 05:17:59
【问题描述】:

我正在解析 HTML 获取与特定 url 匹配的所有 hrefs(我们称之为“目标 url”),然后获取锚文本。我尝试过 LinkExtractor、TokenParser、Mechanize、TreeBuilder 模块。对于以下 HTML:

 <a href="target_url">
 <img src=somepath/nw.gf alt="Open this result in new window"> 
 </a>

他们都将“在新窗口中打开此结果”作为锚文本。 理想情况下,我希望看到返回的空白值或类似“图像”的字符串,以便我知道没有锚文本,但 href 仍然与目标 URL 匹配(http://www.yahoo.com em> 在这种情况下)。有没有办法使用其他模块或 Perl 正则表达式来获得所需的结果?

谢谢,

【问题讨论】:

  • 我编辑了您的帖子以显示我认为您想说的话。请显示您尝试解析的确切 HTML。除了将其包含在问题中之外,请勿以任何方式对其进行编辑。

标签: html perl url


【解决方案1】:

您应该发布一些您尝试使用“LinkExtractor、TokenParser、Mechanize 和 TreeBuilder”的示例,以便我们为您提供帮助。

这是pQuery 中对我有用的东西:

use pQuery;

my $data = '
  <html>
    <a href="http://www.something.com">Not yahoo anchor text</a>
    <a href="http://www.yahoo.com"><img src="somepath/nw.gif" alt="Open this result in new window"></img></a>
    <a href="http://www.yahoo.com">just text for yahoo</a>
    <a href="http://www.yahoo.com">anchor text only<img src="blah" alt="alt text"/></a>
  </html>
';

pQuery( $data )->find( 'a' )->each(
    sub {
        say $_->innerHTML 
            if $_->getAttribute( 'href' ) eq 'http://www.yahoo.com';
    }
);

# produces:
#
# => <img alt="Open this result in new window" src="somepath/nw.gif"></img>
# => just text for yahoo
# => anchor text only<img /="/" alt="alt text" src="blah"></img>
#

如果你只想要文本:

pQuery( $data )->find( 'a' )->each(
    sub {
        return unless $_->getAttribute( 'href' ) eq 'http://www.yahoo.com';

        if ( my $text = pQuery($_)->text ) { say $text }
    }
);

# produces:
#
# => just text for yahoo
# => anchor text only
#

/I3az/

【讨论】:

  • 当我运行上面的 pquery 脚本时,为什么我没有看到任何输出?
  • 您是否遇到任何错误?注意。对于say,你需要 perl 5.10.* 或 Perl6::Say 模块。
【解决方案2】:

使用适当的解析器(如 HTML::Parser 或 HTML::TreeBuilder)。使用正则表达式来解析 SGML(包括 HTML/XML)并不是那么有效,因为有趣的多行标签和属性就像你遇到的那样。

【讨论】:

    【解决方案3】:

    如果您使用的 HTML 非常接近格式良好,您通常可以将其加载到支持 HTML 的 XML 模块中,并使用它从您感兴趣的文档部分中查找和提取数据。 我选择的方法是 XML::LibXML 和 XPath。

    use XML::LibXML;
    
    my $parser = XML::LibXML->new();
    my $html = ...;
    my $doc = $parser->parse_html_string($html);
    
    my @links = $doc->findnodes('//a[@href = "http://example.com"]');
    for my $node (@links) {
        say $node->textContent();
    }
    

    传递给 findnodes 的字符串是一个 XPath 表达式,它查找 $doc 的所有“a”元素后代,其 href 属性等于“http://example.com”。

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多