gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:39:38 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com