rpb
rpb

Reputation: 3299

How to optimise the code evaluation in Selenium with Python

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?

Upvotes: 1

Views: 47

Answers (1)

KunduK
KunduK

Reputation: 33384

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")

Upvotes: 1

Related Questions