簡體   English   中英

如何在Perl中提取URL標記並從HTML鏈接文本?

[英]How can I extract URL tags and link text from HTML in Perl?

我有一個包含以下內容的頁面:

<a href="http://www.trial.com" title="yellow">Trial</a>
<a href="http://www.trial1.com" title="red">Trial2</a>

如何獲取錨文本,URL和標題?

我想要這個輸出:

Trial, http://www.trial.com, yellow
Trial2, http://www.trial1.com, red

我已經嘗試使用WWW :: Mechanize ,如此處所述 ,但我不知道如何以這種方式獲得標題。 你有什么想法?

簡單版本,根據您的問題

  • 看起來像您的頁面(因此,不會混淆的html可能會搞亂)
  • 所需的輸出

這可能是您要尋找的:

use strict;
use warnings;

use WWW::Mechanize;

my $mech = WWW::Mechanize->new;
$mech->get('file:page.html');

foreach my $link ($mech->links) {
    my $text  = $link->text;
    my $url   = $link->url;
    my $title = $link->attrs->{title};

    print "$text, $url, $title\n"
}

快樂編碼,TIMTOWTDI

使用問題中提供的文檔。 我創造了可以解決您所相信的問題的東西。 顯然,使用https://www.perlmonks.org存在一些異常,因為某些URL不是完整的URL,但是通過一些簡單的檢查和跳過(如果不是所需的話),我想您會得到所需的。

示例輸出

_____________________________________________________________________________________________________________________________
| Text                                            | URL                | Attributes
_____________________________________________________________________________________________________________________________
| Testing a metacpan dist with XS components      | ?node_id=1216149   | [name]post-head-id1216149[id]post-head-id1216149,  |
| Controlling the count in array                  | ?node_id=1216134   | [name]post-head-id1216134[id]post-head-id1216134,  |

可能您對hashref感到困惑。 您只需要創建一個for循環來遍歷那些,即可獲取屬性標簽及其值。

碼:

#!/usr/bin/perl
# your code goes here
use strict;
use warnings;
use Data::Dumper;
use WWW::Mechanize ();
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;

my @urls = (
    q{https://www.perlmonks.org/}
);

my $mech = WWW::Mechanize->new();
$mech->get(@urls);

my @links = $mech->links();
print qq{______________________________________________________________________________________________________________\n};
printf(qq{| %-65s | %-75s | %-25s\n},q{Text},q{URL},q{Attributes});
print qq{______________________________________________________________________________________________________________\n};
foreach my $link (@links) {
    if ($link->text() && $link->url()) {
        my $a;
        foreach my $attr (keys %{$link->attrs()}) {
            next if $attr =~ m/href/i;

            #$link->attr()->{$attr} is the value of the key in this hashref. 
            $a .= qq{[$attr]} . $link->attrs()->{$attr};
        }
        my $info;
        if ($a) {
            $info = sprintf(qq{| %-65s | %-75s | %-25s, },$link->text(),$link->url(),$a);
        } else {
            $info = sprintf(qq{| %-65s | %-75s |},$link->text(),$link->url());
        }
        print $info . qq{ |\n};
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM