Improve stale element handling
(cherry picked from commit c0b1037)
strip out whitespaces
(cherry picked from commit 20c6ec9)