Skip to main content
 首页 » 编程设计

python之如何处理 Python Selenium 重复加载模式并保持 DRY

2024年09月07日8davidwang456

我正在使用 python 3.6 和 selenium 3.8.1,Chrome 浏览器来模拟用户输入订单。我们使用的应用程序有一个特别令人沮丧的自动化实现 - 加载产品过滤器时会弹出一个加载模式,但它并没有真正覆盖它下面的元素。此外,加载时间波动很大,但有上限。如果我不使用过多的 sleep 语句,selenium 要么在加载正确的对象之前开始疯狂点击,要么点击元素,但当然会点击加载模式。 (有趣的旁注,加载模式仅填充屏幕 View ,因此 selenium 也能够与首屏下的项目进行交互。:P)

为了解决这个问题:

def kill_evil_loading_modal(self): 
    # i pause for a second to make sure the loader has a chance to pop 
    time.sleep(1) 
 
    # pulling locator type and from another file: ("id","locator_id") 
    loading_modal = ProductsLocators.loading_modal_selector 
 
    # call a function that returns true/false for object if exists 
    check_for_evil = self.is_element_exist(*loading_modal) 
 
    while check_for_evil == True: 
        check_for_evil = self.is_element_exist(*loading_modal) 

这很好用!在我有大量邪恶的 time.sleep(x) 语句来避免加载模式的地方,我现在捕获它并等待它继续前进。

如果我只需要处理两到三次,我就会继续前进。遗憾的是,此加载模式在每次点击 后发生...所以这就是我的主脚本现在的样子:

 new_quote02_obj.edit_quote_job(**data) 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.click_product_dropdown() 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.click_product_dropdown_link() 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.select_category_dropdown(scenario_data['category_name']) 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.select_market_dropdown(scenario_data['local_sales_market']) 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.add_products_job(scenario_data['product_list_original']) 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.click_done_btn() 
 new_quote03_obj.kill_evil_loading_modal() 
 new_quote03_obj.next_btn_page() 

我如何重构以保持 DRY?

请您参考如下方法:

如果您想等到模态消失并避免使用time.sleep(),您可以尝试ExplicitWait :

from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait as wait 
 
wait(driver, 10).until_not(EC.visibility_of_element_located(("id", "locator_id"))) 

或

wait(driver, 10).until(EC.invisibility_of_element_located(("id", "locator_id"))) 

这应该允许您最多等待 10 秒(如果需要增加延迟),直到具有指定选择器(“id”、“locator_id”)的元素变得不可见

如果在每次点击后出现模态,您可以实现自己的点击方法,例如

def click_n_wait(by, value, timeout=10): 
    wait(driver, timeout).until(EC.element_to_be_clickable((by, value))).click() 
    wait(driver, timeout).until(EC.invisibility_of_element_located(("id", "locator_id"))) 

并将其用作

click_n_wait("id", "button_id")