Refactored so as to overcome potential memory issues caused by usage of lxml smart_strings