【发布时间】:2017-05-01 18:54:30
【问题描述】:
我正在尝试将 HTML 网页中的文本和标签提取到文本文件中。
这里是输入的网页内容(在view:source模式下查看时):
<div class="moduleBody">In addition, <b>ABC provides</b> dual finishing and detailing <u>products</u>, including a system of cleaners, dressings, polishes, waxes and other products.</p><p></p><p>Safety and Graphics Business</p><p></p><p>The Safety and Graphics segment serves a range of markets for the safety, security and productivity of people, facilities and systems. Its <b>product offerings</b> include personal protection products, such as <u>respiratory, hearing, eye and fall protection</u> equipment;<div class="moreLink">
以下代码在单独提取文本时工作正常,但它正在取消 <p>、</p>、<u>、</u>、<b> 和 </b> 以及其他 HTML 标记,我想保留它。
use WWW::Mechanize;
use threads;
my $mech = WWW::Mechanize->new;
my $Lvalue = "";
$mech->get($link);
$mech->quiet(1);
my $p = HTML::TokeParser->new(\$mech->content);
while ( my $tag1 = $p->get_tag('div') ) {
if ( $tag1->[1]{class} and $tag1->[1]{class} eq 'moduleBody' ) {
$Lvalue = $p->get_trimmed_text("moreLink");
$Lvalue =~ s/$find1/|/g;
$Lvalue =~ s/$find2/|/g;
print $fh "$ticker^|$Lvalue\n";
}
}
上面代码的输出是:
In addition, ABC provides dual finishing and detailing products, including a system of cleaners, dressings, polishes, waxes and other products. Safety and Graphics Business The Safety and Graphics segment serves a range of markets for the safety, security and productivity of people, facilities and systems. Its product offerings include personal protection products, such as respiratory, hearing, eye and fall protection equipment;
实际上,我的代码正在删除我想要保留的 HTML 标记。 我觉得可能需要调整“get_trimmed_text”以保留 p、/p、b 和 /b(以及其他 html)标签。 有人可以帮助对代码进行任何必要的更改吗?
明确说明要求:
我正在寻找一个 perl 函数,它可以帮助提取位于网页上“<div class="moduleBody">”和“<div class="moreLink">”之间的(TEXT+ ALL HTML TAGS)(如上面的示例输入文本中所引用)。我愿意使用除 get_trimmed_text 之外的其他功能。
非常感谢。
回答此问题 - 面向普通观众
@SinanÜnür 提供的回复效果很好。谢谢@SinanÜnür! +1 并将其标记为答案。
为了广大观众的利益,请注意,只要您将 HTML 内容保留在“my $html = <<HTML;”变量中,Sinan Ünür 的代码就可以正常工作。如果您正在阅读 URL,则需要对代码进行一些调整以包含以下内容:
use LWP::Simple;
my $url = "http://www.example.com/profile?item=66&class=XYZ";
my $html = get($url);
【问题讨论】:
-
好吧,我提供了一个独立的例子。您可以根据自己获取源 HTML 的方式来调整它。
标签: perl