Update code to be more robust and avoid NoSuchElement.