1

I would like to extract the span text located within the class SOME_CLASS_NAME. The class SOME_CLASS_NAME might not always available. Also, it take some time before the class properly visible if it does exist.

To handle this, the following code were propsed.

Dirty workaround to check whether the class available or not

size_len = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located(
                    (By.XPATH, './/span[@class = "SOME_CLASS_NAME"]')))

OR

 if len( self.browser.find_elements_by_xpath('.//span[@class = "SOME_CLASS_NAME"]') ) > 0 :  
        element =self.browser.find_elements_by_xpath( './/span[@class = "SOME_CLASS_NAME"]' )[ 0 ].text
    
 else:
         element = '0'

While the above approach work, but,I found it very inefficient to evaluate the class for 3 times.

May I know if there is a way to make the above code more efficient?

1 Answer 1

1

Use try..except block and use visibility_of_element_located() instead presence_of_element_located()

try:
    print(WebDriverWait(self.browser, 10).until(EC.visibility_of_element_located((By.XPATH, './/span[@class = "SOME_CLASS_NAME"]'))).text)
except:
    print("element no available")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. Should the TimeoutException: be there? or this is some special case?
@balandongiv : You can use ` except TimeoutException:` If you want but with that you can't continue further.if you want continue to the next step then use except.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.