I have around 20 elements to find by xpath. I'm using this.
e1 = element.find_element_by_xpath('.//div[contains(@class, "myclass")]').text
When element is not found, it throws NoSuchElementException.
One solution would be to use: find_elements_by_xpath instead.
e1 = element.find_elements_by_xpath('.//div[contains(@class, "myclass")]')
# Then check for length
if len(e1) > 0:
text1 = e1[0].text
That's 3 lines of codes for one single element.
If I use try, except as well, there will be 60 lines of code
more for such a trivial task.
How to handle this elegantly? Also, is there any way to find text directly from xpath instead of doing element.text like:
# This should return text inside of that element
text = element.find_element_by_xpath('.//div[contains(@class, "myclass")]/text()')