perl 中的 HTML 解析 [英] HTML parsing in perl

查看:37
本文介绍了perl 中的 HTML 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 perl 解析以下 HTML 结构.我需要选择包含类消息和 id 的所有 dd 元素.我想让脚本做的就是遍历所有 dd 元素并打印出 dd 元素的 id 但它需要忽略第一个 dd 元素,因为它是静态的,不会改变.

它可以与任何 perl 模块一起使用,只要它可以从 cpan 安装,这对我来说很容易.我在 perl 和解析 html 方面没有太多经验,所以任何指针都会非常有帮助.

谢谢:)

HTML 结构:

<头><身体>.....其他元素<div id="消息"><div class="header"></div><dl><dd class="message unread mc-friend mc-message">这只是一条随机消息,请勿解析</dd><dd id="msg2" class="message unread mc-message">你好

<dd id="msg3" class="message unread mc-message">你好</dd></dl>

</pre></code>

解决方案

像这样,快速而简单:

#!/usr/bin/perl使用严格;使用警告;使用 Mojo::DOM;my $html = "你的 HTML 在这里";我的 $dom = Mojo::DOM->new;$dom->parse($html);我的$skip;对于我的 $dd ($dom->find('dd[class*="message"]')->each) {打印 $dd->attrs->{id}, "
" if $skip++;}

I'm trying to parse the following HTML structure with in perl. I need to select all of the dd elements that contain the class message and also an id. All I would like the script to do is loop through all of the dd elements and print out the id of the dd element but it needs to ignore the first dd element as that is static and will not change.

It can be with any perl module as long as it can be installed from cpan to make it easy for me. I don't have much experience with perl and parsing html so any pointers would be very helpful.

Thanks :)

HTML Structure:

<pre><code>
<html>
<head>
</head>
<body>
 .....other elements
    <div id="messages">
        <div class="header"></div>
        <dl>
            <dd class="message unread mc-friend mc-message">This is just a random message, do not parse</dd>
            <dd id="msg2" class="message unread mc-message">
                Hello
            </div>
            <dd id="msg3" class="message unread mc-message">
                Hello
            </dd>
        </dl>
    </div>
</body>
</html>
</pre></code>

解决方案

Something like this, quick and easy:

#! /usr/bin/perl
use strict;
use warnings;

use Mojo::DOM;

my $html = "Your HTML goes here";

my $dom = Mojo::DOM->new;
$dom->parse($html);
my $skip;
for my $dd ($dom->find('dd[class*="message"]')->each) {
    print $dd->attrs->{id}, "
" if $skip++;
}

这篇关于perl 中的 HTML 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆