Como faço para extrair um título HTML com Perl?
Pergunta
Existe uma maneira de extrair o título da página HTML usando Perl? Eu sei que pode ser passado como uma variável oculto durante envio de formulário e, em seguida, recuperados em Perl dessa forma, mas eu queria saber se existe uma maneira de fazer isso sem o enviar?
Como, digamos que eu tenho uma página HTML como esta:
<html><head><title>TEST</title></head></html>
e, em seguida, em Perl que eu quero fazer:
$q -> h1('something');
Como posso substituir 'algo' de forma dinâmica com o que está contido em tags
Solução
Gostaria de usar pQuery . Ele funciona exatamente como jQuery.
Você pode dizer:
use pQuery;
my $page = pQuery("http://google.com/");
my $title = $page->find('title');
say "The title is: ", $title->html;
material substituição é semelhante:
$title->html('New Title');
say "The entirety of google.com with my new title is: ", $page->html;
Você pode passar uma string HTML para o construtor pQuery
, que parece que você quer fazer.
Finalmente, se você quiser usar arbitrário HTML como um "modelo", e depois "refinar" que, com comandos Perl, você quer usar Molde :: Refine .
Outras dicas
HTML :: HeadParser faz isso para você.
Não está claro para mim o que você está pedindo. Você parece estar falando de algo que poderia funcionar no navegador do usuário, ou pelo menos algo que já tenha uma página html carregado.
Se Isso é não o caso, a resposta é URI: :. Título
use strict;
use LWP::Simple;
my $url = 'http://www.google.com'|| die "Specify URL on the cmd line";
my $html = get ($url);
$html =~ m{<TITLE>(.*?)</TITLE>}gism;
print "$1\n";
A resposta anterior é errado, se o título de tag HTML é usado com mais freqüência, então isso pode ser facilmente superada pela verificação para certificar-se de que o título de tag é válido (sem marcas no meio).
my ($title) = $test_content =~ m/<title>([a-zA-Z\/][^>]+)<\/title>/si;
get a forma nome do título do arquivo.
my $spool = 0;
open my $fh, "<", $absPath or die $!;
#open ($fh, "<$tempfile" );
# wrtie the opening brace
print WFL "[";
while (<$fh>) {
# removes the new line from the line read
chomp;
# removes the leading and trailing spaces.
$_=~ s/^\s+|\s+$//g;
# case where the <title> and </title> occures in one line
# we print and exit in one instant
if (($_=~/$startstring/i)&&($_=~/$endstring/i)) {
print WFL "'";
my ($title) = $_=~ m/$startstring(.+)$endstring/si;
print WFL "$title";
print WFL "',";
last;
}
# case when the <title> is in one line and </title> is in other line
#starting <title> string is found in the line
elsif ($_=~/$startstring/i) {
print WFL "'";
# extract everything after <title> but nothing before <title>
my ($title) = $_=~ m/$startstring(.+)/si;
print WFL "$title";
$spool = 1;
}
# ending string </title> is found
elsif ($_=~/$endstring/i) {
# read everything before </title> and nothing above that
my ($title) = $_=~ m/(.+)$endstring/si;
print WFL " ";
print WFL "$title";
print WFL "',";
$spool = 0;
last;
}
# this will useful in reading all line between <title> and </title>
elsif ($spool == 1) {
print WFL " ";
print WFL "$_";
}
}
close $fh;
# end of getting the title name
Se você quiser apenas para extrair o título da página que você pode usar uma expressão regular. Eu acredito que seria algo como:
my ($title) = $html =~ m/<title>(.+)<\/title>/si;
onde sua página HTML é armazenado no $html
string. Em si
, o s
significa para modo de linha única (ou seja, o ponto também coincide com uma nova linha) e i
para ignorar caso .