You probably need to wait for the document to be loaded completely before parsing.
Something like this.