Come faccio a trovare i contenuti di un div con moduli HTML del Perl, se conosco un tag all'interno di esso?

StackOverflow https://stackoverflow.com/questions/1692362

  •  18-09-2019
  •  | 
  •  

Domanda

Da quando ho chiesto come analizzare HTML con regex, ma ho sbattuto un po '(giustamente), ho studiato HTML :: TreeBuilder , HTML :: Parser , HTML :: TokeParser , e HTML :: Elementi moduli Perl.

Ho HTML in questo modo:

<div id="listSubtitlesFilm">
  <dt id="a1">
    <a href="/45/subtitles-67624.aspx">
      .45 (2006)
    </a>
  </dt>
</div>

Voglio analizzare la /45/subtitles-67624.asp, ma ancora più importante Vorrei sapere come analizzare il contenuto del div .

Mi è stato dato questo esempio su una domanda precedente:

while ( my $anchor = $parser->get_tag('a') ) {
    if ( my $href = $anchor->get_attr('href') ) {
 #http://subscene.com/english/Sit-Down-Shut-Up-First-Season/subtitles-272112.aspx
        push @dnldLinks, $1 if $href =~ m!/subtitle-(\d{2,8})\.aspx!;
    }

Questo ha funzionato perfettamente per questo, ma quando ho provato a modificare un po 'e usarlo su un `` div` non ha funzionato. Ecco il codice che ho provato:

Ho provato ad utilizzare questo codice:

while (my $anchor = $p->get_tag("dt")) {
  if($stuff = $anchor->get_attr('a1')) {
    print $stuff."\n";
  }
}
È stato utile?

Soluzione

Per rispondere, la tua domanda specifica, dato il codice HTML:

<div id="listSubtitlesFilm">
  <dt id="a1">
    <a href="/45/subtitles-67624.aspx">
      .45 (2006)
    </a>
  </dt>
</div>

Io parto dal presupposto che vi interessa nel testo di ancoraggio, cioè ".45 (2006)", in questo caso, ma solo se l'ancora si verifica in un div con id listSubtitlesFilm.

#!/usr/bin/perl

use strict;
use warnings;

use HTML::TokeParser::Simple;

my $parser = HTML::TokeParser::Simple->new(handle => \*DATA);

my @dnldLinks;

while ( my $div = $parser->get_tag('div') ) {
    my $id = $div->get_attr('id');
    next unless defined($id) and $id eq 'listSubtitlesFilm';

    my $anchor = $parser->get_tag('a');
    my $href = $anchor->get_attr('href');
    next unless defined($href)
        and $href =~ m!/subtitles-(\d{2,8})\.aspx\z!;
    push @dnldLinks, [$parser->get_trimmed_text('/a'), $1];
}

use Data::Dumper;
print Dumper \@dnldLinks;


__DATA__
<div id="listSubtitlesFilm">
  <dt id="a1">
    <a href="/45/subtitles-67624.aspx">
      .45 (2006)
    </a>
  </dt>
</div>

Output:

$VAR1 = [
          [
            '.45 (2006)',
            '67624'
          ]
        ];

Altri suggerimenti

Si potrebbe utilizzare (ancora un altro modulo!) HTML :: :: TreeBuilder XPath , che, come per il suo nome, vi permetterà di usare XPath su oggetti HTML :: TreeBuilder.

#!/usr/bin/perl

use strict;
use warnings;

use HTML::TreeBuilder::XPath;

my $root = HTML::TreeBuilder::XPath->new_from_file( "my.html");

# print $root->as_HTML; # useful to see how HTML::TreeBuilder
# understands your HTML. For example it will wrap the implied
# dl element around dt, which you need to take into account
# when writing the XPath query below

my $id= "a1";
# you need the .//dt because of the extra dl
my @divs= $root->findnodes( qq{//div[.//dt[\@id="$id"]]});

print $divs[0]->as_HTML; # or as_text

Codice utilizzando HTML::TreeBuilder:

use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new_from_content($html);

for my $link ($tree->look_down(
  _tag => 'a', 
  href => qr{/subtitle-\d{2,8}\.aspx})
) {
  my $linkid = $link->attr('href') =~ m!/subtitle-\d{2,8}\.aspx!;
  # Scalar context gets the first, and the first is the nearest parent
  my $parent_div = $link->look_up(_tag => 'div');
  # Now the interesting bit of the link is in $linkid, the parent div ID
  # is $parent_div->id or $parent_div->attr_id, and its text is e.g.
  # $parent_div->as_trimmed_text or you can do other stuff with its content.
}

È necessario modificare il get_attr("a1") a get_attr("id") qui. Il get_attr (x) è alla ricerca di un attributo con il nome x, ma si sta dando il valore dell'attributo, non il suo nome.

Per inciso il tag <dt> non è un <div>, è il tag oggetto per un <dl> (elenco di definizioni).

get_attr('a1') avrebbe dovuto probabilmente letto get_attr('id') e sarebbe stampare "A1"

Credo che ricevendo il contenuto del testo sarebbe simile:

while ( my $anchor = $parser->get_tag('div') ) {
  my $content = $parser-get_text('/div');
}

Se si intende il contenuto del testo del collegamento sarebbe:

while ( my $anchor = $parser->get_tag('a') ) {
    if ( my $href = $anchor->get_attr('href') ) {
        my $content = $parser->get_text('/a');
#http://subscene.com/english/Sit-Down-Shut-Up-First-Season/subtitle-272112.aspx
        push @dnldLinks, $1 if $href =~ m!/subtitle-(\d{2,8})\.aspx!;
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top