【问题标题】:how to bypass html escape signs and extract text only from html file in perl using web::scraper如何使用 web::scraper 绕过 html 转义符号并仅从 perl 中的 html 文件中提取文本
【发布时间】:2013-02-21 14:32:26
【问题描述】:

我试图仅从 html 页面中提取文本,并希望忽略或绕过 html 转义符号“”。我正在复制用于提取文本的 html 页面部分:

        <table class="reference">
    <tr>
    <th align="left" width="25%">Tag</th>
    <th align="left" width="75%">Description</th>
    </tr>
    <tr>
    <td><a href="tag_comment.asp">&lt;!--...--&gt;</a></td>
    <td>Defines a comment</td>
    </tr>
    <tr>
    <td><a href="tag_doctype.asp">&lt;!DOCTYPE&gt;</a>&nbsp;</td>
    <td>Defines the document type</td>
    </tr>
    <tr>
    <td><a href="tag_a.asp">&lt;a&gt;</a></td>
    <td>Defines a hyperlink</td>
    </tr>
    <tr>
    <td><a href="tag_abbr.asp">&lt;abbr&gt;</a></td>
    <td>Defines an abbreviation</td>
    </tr>
    <tr>
...

我的 perl 代码是:

my $urlToScrape = "http://www.w3schools.com/tags/";

# prepare data
my $teamsdata = scraper {
process "table.reference > tr > td > a ", 'tags[]' => 'TEXT';
process "table.reference > tr > td > a ", 'urls[]' => '@href';
};

# scrape the data
my $res = $teamsdata->scrape(URI->new($urlToScrape));

print "<HTML_tags>\n";
for my $i ( 0 .. $#{$res->{urls}}) {
 print FILE "   <tag_Name> $res->{tags}[$i] </tag_Name>\n ";
}
print "</HTML_tags>\n";

我得到的输出如下:

<HTML_tags>
    <tag_Name> <!--...--> </tag_Name>
        <tag_Name> <!DOCTYPE> </tag_Name>
        <tag_Name> <a> </tag_Name>
        <tag_Name> <abbr> </tag_Name>
</HTML_tags>

而我希望输出为:

<HTML_tags>
    <tag_Name> !--...-- </tag_Name>
        <tag_Name> !DOCTYPE </tag_Name>
        <tag_Name> a </tag_Name>
        <tag_Name> abbr </tag_Name>
</HTML_tags>

谁能告诉我必须改变什么才能获得上述输出? 非常感谢。

【问题讨论】:

    标签: html perl web-scraping


    【解决方案1】:

    蛮力:

    $res->{tags}[$i] =~ s/[\<\>]//gs; ## Added line 
    print FILE "   <tag_Name> $res->{tags}[$i] </tag_Name>\n ";
    

    【讨论】:

    • 非常感谢。它对我有用。你能告诉我这里的/s是什么意思吗?我知道 /g 它将“当前字符串”中任何出现的确切字符序列“”替换为任何内容。
    猜你喜欢
    • 1970-01-01
    • 2012-01-23
    • 2011-08-16
    • 2014-12-08
    • 2021-09-23
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多