简体   繁体   English

如何使用 Python 优化 Selenium 中的代码评估

[英]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 .我想提取位于class SOME_CLASS_NAME中的跨度文本。 The class SOME_CLASS_NAME might not always available. class SOME_CLASS_NAME可能并不总是可用。 Also, it take some time before the class properly visible if it does exist.此外,如果 class 确实存在,它需要一些时间才能正确显示。

To handle this, the following code were propsed.为了解决这个问题,提出了以下代码。

Dirty workaround to check whether the class available or not检查 class 是否可用的肮脏解决方法

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.虽然上述方法有效,但是,我发现对 class 进行 3 次评估非常低效。

May I know if there is a way to make the above code more efficient?请问有没有办法让上面的代码更有效率?

Use try..except block and use visibility_of_element_located () instead presence_of_element_located ()使用 try..except 块并使用visibility_of_element_located () 而不是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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM