TextExpander: HTML Hyperlink Page Title from URL

I have frequently found myself needing to add a link into a blog post for an existing web page where I’d like to link it as the page title. Rather than a couple of copy and paste actions I decided to create a TextExpander snippet to do the (not particularly) heavy lifting for me.

In order to produce this functionality we’re going to use the clipboard as the place to hold the URL we wish to get the page title for. This means that the first thing you’ll need to do is copy the URL you want to use - quite easy if you happen to have it in your web browser.

With the URL on the clipboard I then use TextExpander to call a PERL script that produces the HTML for the hyperlink. The script takes the URL and reads in the HTML for the page addressed by this URL. It then locates the text contained between ‘title’ tags. This title text is also then stripped of any leading or trailing white space (I’ve had a few pages where there are extra spaces and I don’t want these being included in the hyperlink). Finally the URL and title are combined into HTML for a hyperlink which is then returned to and output by TextExpander.

Details of the snippet are given below.

Label HTML Link using Page Title from URL (PERL)
Description Generate HTML hyperlink including page title from a URL on the clipboard.
Abbreviation htmllink
Content
#!/usr/bin/perl -w

#Initialise
use strict;
use LWP::Simple;

#Get the URL from the clipboard
my $text =`pbpaste`;

#Get the page content
my $url = $text || die "";
my $html = get ($url);

#Get the page title
$html =~ m{<TITLE>(.*?)</TITLE>}gism;
my $title = $1;

#Remove any leading or trailing white space
$title=~ s/^\s+|\s+$//g;

#Output the HTML link
print "<a href='$url'>$title</a>";

This snippet can be downloaded as part of the Thought Asylum web snippet group.

Author: Stephen Millard
Tags: | perl | textexpander |

Buy me a coffeeBuy me a coffee



Related posts that you may also like to read