【问题标题】:I'm not getting HTML tag while parsing解析时我没有得到 HTML 标签
【发布时间】:2015-10-06 17:55:45
【问题描述】:

我要解析的 HTML 代码片段是这样的:

<ul class="authors">
    <li class="author" itemprop="author" itemscope="itemscope" itemtype="http://schema.org/Person">
        <a href="/search?facet-creator=%22Charles+L.+Fefferman%22" itemprop="name">Charles L. Fefferman</a>,
    </li>
    <li class="author" itemprop="author" itemscope="itemscope" itemtype="http://schema.org/Person">
        <a href="/search?facet-creator=%22Jos%C3%A9+L.+Rodrigo%22" itemprop="name">José L. Rodrigo</a>
    </li>

我想提取整个 &lt;a&gt; 元素,但是当我试图用 WWW::Mechanize::TreeBuilder 解析它时,我得到的唯一内容是作者的名字。所以:

我期待的内容:

<a href="/search?facet-creator=%22Charles+L.+Fefferman%22" itemprop="name">Charles L. Fefferman</a>,

<a href="/search?facet-creator=%22Jos%C3%A9+L.+Rodrigo%22" itemprop="name">José L. Rodrigo</a>

我收到的内容:

Charles L. Fefferman,
José L. Rodrigo

下面是负责解析的代码:

my $mech = WWW::Mechanize->new();
WWW::Mechanize::TreeBuilder->meta->apply($mech);
$mech->get($addressdio);

my @authors = $mech->look_down('class', 'author');

print "Authors: <br />";
foreach ( @authors ) {
    say $_->as_text(), "<br />";
}

我认为这可能与as_text() 有关,而且当 CGI 获取 HTML 时,它不会将其作为文本。

【问题讨论】:

  • 请将您的解决方案作为问题的答案发布并接受。这样其他人会找到它,而试图提供帮助的人会更容易看到已经有解决方案。您也可以edit 问题并将其删除,因为它不属于问题,或者只是回滚更改。谢谢。

标签: perl parsing web mechanize


【解决方案1】:

我处理了它,但方式完全不同 - 使用 HTML::TagParser:

my $html = HTML::TagParser->new("overwrite.xml");
my @li = $html->getElementsByAttribute('class','author');

foreach(@li){
    my $a = $_->firstChild();
    my $link = $a->getAttribute('href');
    say $_->innerText;

    say $link;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多