我正在解析HTML,获取与特定网址匹配的所有href
(让我们称之为“目标网址”),然后获取锚文本。我尝试过LinkExtractor,TokenParser,Mechanize,TreeBuilder模块。对于以下HTML:
<a href="target_url">
<img src=somepath/nw.gf alt="Open this result in new window">
</a>
所有这些都将“在新窗口中打开此结果”作为锚文本。
理想情况下,我希望看到空白值或返回“image”之类的字符串,以便我知道没有锚文本,但href
仍然与目标网址匹配( http://www.yahoo.com 在这种情况下)。有没有办法使用其他模块或Perl正则表达式获得所需的结果?
谢谢,
答案 0 :(得分:3)
您应该发布一些您尝试使用“ LinkExtractor,TokenParser,Mechanize&amp; 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 /
答案 1 :(得分:1)
使用正确的解析器(如HTML :: Parser或HTML :: TreeBuilder)。使用正则表达式来解析SGML(包含HTML / XML)并不是那么有效,因为有趣的多行标记和属性就像你遇到过的那样。
答案 2 :(得分:0)
如果您正在使用的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”。