You can check the title of an open window using wmctrl:
$ wmctrl -lx | grep "last.fm.Last.fm" | grep -Po "(?<=$HOSTNAME ).*$"
Insomnium – Death Walked the Earth
Watching the title using this method would require the script to periodically poll for changes, though, which would be messy and inefficient.
A smarter approach would be to wait for some kind of event generated by the Last.fm player. A D-Bus interface or similar API would be ideal, but I don't see any documentation suggesting one exists. As a next-best alternative, you can try watching the terminal output for information on what the player is doing:
#!/bin/bash
grabnextline=0
albumart="$(mktemp)"
while read line; do
if [ $grabnextline = 1 ]; then
title="$(echo "$line" | cut -d\" -f2)"
wget -O "$albumart" "$(grep -A 10 "<title>$(echo "$title" | awk -F ' – ' '{print $2}')" ~/.local/share/Last.fm/Last.fm.log | grep -Eo "http://.*\.(jpg|png)" | sed 's/174s/64s/' | sed 's/jpg/png/')"
notify-send "$title" --icon "$albumart"
grabnextline=0
fi
if [[ "$line" = *ScrobblerManager::nowPlaying* ]]; then
grabnextline=1
fi
done < <( /usr/bin/lastfm 2>&1 )
rm "$albumart"
exit
It's still an ugly hack, but it gets the job done.