tags:

views:

834

answers:

5

hi

Is there a way to extract HTML page title using Perl? I know it can be passed as a hidden variable during form submit and then retrieved in Perl that way but I was wondering if there is a way to do this without the submit?

Like, lets say i have an HTML page like this:

<html><head><title>TEST</title></head></html>

and then in Perl I want to do :

$q -> h1('something');

How can I replace 'something' dynamically with what is contained in <title> tags?

+6  A: 

I would use pQuery. It works just like jQuery.

You can say:

use pQuery;
my $page = pQuery("http://google.com/");
my $title = $page->find('title');
say "The title is: ", $title->html;

Replacing stuff is similar:

$title->html('New Title');
say "The entirety of google.com with my new title is: ", $page->html;

You can pass an HTML string to the pQuery constructor, which it sounds like you want to do.

Finally, if you want to use arbitrary HTML as a "template", and then "refine" that with Perl commands, you want to use Template::Refine.

jrockway
A: 

If you just want to extract the page title you can use a regular expression. I believe that would be something like:

my ($title) = $html =~ m/<title>(.+)<\/title>/si;

where your HTML page is stored in the string $html. In si, the s stands for for single line mode (i.e., the dot also matches a newline) and i for ignore case.

Results will be not what what you want if there's another </title> on the page after the end of the actual title.In general, regular expressions for HTML parsing is a limited proposition.
Andy Lester
+1  A: 

It's not clear to me what you are asking. You seem to be talking about something that could run in the user's browser, or at least something that already has an html page loaded.

If that's not the case, the answer is URI::Title.

ysth
+2  A: 

HTML::HeadParser does this for you.

brian d foy
The link you posted returns search results that does not return HTML::HeadParser. I had to look around for it: http://search.cpan.org/~gaas/HTML-Parser/
gpojd
Ah, yes, the HTML::HeadParser module comes with HTML::Parser.
brian d foy
A: 

use strict; use LWP::Simple;

my $url = 'http://www.google.com'|| die "Specify URL on the cmd line"; my $html = get ($url); $html =~ m{(.*?)}gism;

print "$1\n";

Manish Shukla