Here is what I currently do to get the first element of a page (or parent element):
first_element = page_or_parent.find_element_by_xpath('//*')
The problem I've only just run into recently (Chrome and chromedriver version 84) is that sometimes this throws an exception:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*"}
Calling the same method again usually retrieves the element so I presume the document tree is temporarily unavailable. However, the web driver log doesn't indicate anything strange:
[1597164661.317][INFO]: [d88526be26bd6364d1b0ed2dab9d5733] COMMAND FindElement {
"using": "xpath",
"value": "//*"
}
[1597164661.317][INFO]: Waiting for pending navigations...
[1597164661.317][INFO]: Done waiting for pending navigations. Status: ok
[1597164661.418][INFO]: Waiting for pending navigations...
[1597164661.418][INFO]: Done waiting for pending navigations. Status: ok
[1597164661.418][INFO]: [d88526be26bd6364d1b0ed2dab9d5733] RESPONSE FindElement ERROR no such element: Unable to locate element: {"method":"xpath","selector":"//*"}
(Session info: chrome=84.0.4147.89)
My main question is then how to get the first element reliably?
Is there a better way than using an XPath as I am doing? I thought about find_elements_by_xpath() (plural) but if there's a lot of elements then that's likely to generate a lot of data and run much slower. The only solution I can think of currently is to catch the exception if it occurs, wait/sleep, and then try again but that feels very dirty.