【发布时间】:2017-03-19 02:27:26
【问题描述】:
我正在尝试在 perl 中编写一个 spider,它将解析域中的所有音频标签并尝试从找到的每个音频标签下载相应的
audio/mpeg内容。
下面是我的代码中的一个 sn-p,它使用 HTML::TokeParser 解析 html 以便从 a 标签中提取链接:
my($response, $base, $stream, $pageURL, $tag, $url);
$response = 'http://example.com/page-with-some-audio-content';
$base = URI->new( $response->base )->canonical;
$stream = HTML::TokeParser->new( $response->content_ref );
$pageURL = URI->new( $response->request->uri );
while($tag = $stream->get_tag('a')) {
next unless defined($url = $tag->[1]{'href'});
print $url."\n";
}
上面的代码 sn-p 从给定的 html 页面中提取所有链接。这与 url 散列一起用于循环中,以抓取给定域中的所有页面。
下面是另一个 sn-p 几乎与第一个相同,只是我试图提取 audio 标签 而不是 a 标签:
my($response, $base, $stream, $pageURL, $tag, $url);
$response = 'http://example.com/page-with-some-audio-content';
$base = URI->new( $response->base )->canonical;
$stream = HTML::TokeParser->new( $response->content_ref );
$pageURL = URI->new( $response->request->uri );
while($tag = $stream->get_tag('audio')) {
next unless defined($url = $tag->[1]{'onplaying'});
print $url."\n";
}
由于某种原因,没有检测到 audio 标记。有什么我遗漏的吗?
阅读HTML::TokeParser 文档,我发现我无法提取嵌套 html 元素的属性。
考虑下面的这个标记:
<audio onplaying="podPress_html5_count('http://www.example.com/mp3/Some Mp3 File.mp3', this.id)">
<source src="http://www.example.com/mp3/Some%20Mp3%20File.mp3">
</audio>
我想解析整个 html 以仅提取找到的所有 audio 标记的 src 属性。因此,如果 html 看起来像这样:
<body>
<audio onplaying="podPress_html5_count('http://www.example.com/mp3/Some Mp3 File.mp3', this.id)">
<source src="http://www.example.com/mp3/Some%20Mp3%20File.mp3">
</audio>
<audio onplaying="podPress_html5_count('http://www.example.com/mp3/Some Mp3 File 2.mp3', this.id)">
<source src="http://www.example.com/mp3/Some%20Mp3%20File%202.mp3">
</audio>
<audio onplaying="podPress_html5_count('http://www.example.com/mp3/Some Mp3 File 3.mp3', this.id)">
<source src="http://www.example.com/mp3/Some%20Mp3%20File%203.mp3">
</audio>
<audio onplaying="podPress_html5_count('http://www.example.com/mp3/Some Mp3 File 4.mp3', this.id)">
<source src="http://www.example.com/mp3/Some%20Mp3%20File%204.mp3">
</audio>
</body>
预期的输出应该是这样的:
http://www.example.com/mp3/Some%20Mp3%20File.mp3
http://www.example.com/mp3/Some%20Mp3%20File%202.mp3
http://www.example.com/mp3/Some%20Mp3%20File%203.mp3
http://www.example.com/mp3/Some%20Mp3%20File%204.mp3
所以我需要解析 html 文件以仅提取每个存在的
audio标记的src属性。
【问题讨论】:
-
我担心这个模块不支持 HTML5。
-
@choroba noooohh!!!!!那有什么选择?? X(
标签: perl html-parsing