html - 使用 Perl 从 html 中解析特定文本

标签 html database perl extract

我有一个 html 页面,其中包含我想使用 Perl 脚本将其解析为数据库的特定文本。

我希望能够去掉所有我不想要的东西,html 的一个例子是-

<div class="postbody">
        <h3><a href "foo">Re: John Smith <span class="posthilit">England</span></a></h3>
        <div class="content">Is C# better than Visula Basic?</div>
    </div>

因此我想导入到数据库中

  1. 姓名:约翰·史密斯。
  2. 住在:英格兰。
  3. 评论:C# 是否优于 Visula Basic?

我已经开始创建一个 Perl 脚本,但需要对其进行更改才能满足我的要求;

    use DBI;

    open (FILE, "list") || die "couldn't open the file!";

    open (F1, ">list.csv") || die "couldn't open the file!";

    print F1 "Name\|Lives In\|Commented\n";

    while ($line=<FILE>)

    {

    chop($line);
    $text = "";
    $add = 0;
    open (DATA, $line) || die "couldn't open the data!";
    while ($data=<DATA>)

    {
    if ($data =~ /ds\-div/)
    {
    $data =~ s/\,//g;
    $data =~ s/\"//g;
    $data =~ s/\'//g;
    $text = $text . $data;
    }

    }

    @p = split(/\\/, $line);
    print F1 $p[2];
    print F1 ",";
    print F1 $p[1];
    print F1 ",";
    print F1 $p[1];
    print F1 ",";  

    print F1 "\n";
    $a = $a + 1;

任何输入将不胜感激。

最佳答案

请不要使用正则表达式来解析 HTML,因为 HTML 不是常规语言正则表达式描述正则语言。

使用HTML::TreeBuilder 很容易解析HTML (及其模块系列):

#!/usr/bin/env perl

use warnings;
use strict;

use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new_from_content(
    do { local $/; <DATA> }
);

for ( $tree->look_down( 'class' => 'postbody' ) ) {
    my $location = $_->look_down( 'class' => 'posthilit' )->as_trimmed_text;
    my $comment  = $_->look_down( 'class' => 'content' )->as_trimmed_text;
    my $name     = $_->look_down( '_tag'  => 'h3' )->as_trimmed_text;
    $name =~ s/^Re:\s*//;
    $name =~ s/\s*$location\s*$//;

    print "Name: $name\nLives in: $location\nCommented: $comment\n";
}

__DATA__
<div class="postbody">
    <h3><a href="foo">Re: John Smith <span class="posthilit">England</span></a></h3>
    <div class="content">Is C# better than Visual Basic?</div>
</div>

输出

Name: John Smith
Lives in: England
Commented: Is C# better than Visual Basic?

但是,如果您需要更多控制,请查看 HTML::Parser正如已经answered通过 ADW .

关于html - 使用 Perl 从 html 中解析特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6598480/

相关文章:

java - 保护 Java Web 应用程序不被复制

mysql - 为书籍应用程序设计数据库

iphone - iPhone 中的存储

perl - 如何理解用于评估标记的脚本 conlleval.perl?

html - 隐藏 float 兄弟时自动展开 div

html - 在复制纸张交互的 Web 应用程序的 CSS 上使用 cm/mm 是一个好习惯吗?

html - 仅 CSS : Apply style only on non-hovered siblings

sql - SQL Server 中几个表的一般报告

perl 脚本,用于在 multifasta 文件中搜索主题并将完整序列与标题行一起打印

perl - 为什么 pleenv install-cpanm 安装到错误的位置?