Think about xpath. Although the code will probably be longer and the script will have a dependency, xpath is meant exactly for that kind of tasks.