from playwright.sync_api import sync_playwright with sync_playwright() as playwright: # 省略了start啟動 browser = playwright.chromium.launch(headless=False, slow_mo=1000) # 設定了每步等待時間為3s page = browser.new_page() # 開啟一個頁面 page.goto('https://www.baidu.com/') # 開啟百度地址 page.fill('#kw', 'test') # 搜尋方塊輸入內容 page.click('#su') # 點選搜尋 browser.close() # 省略了關閉playwright物件
""" 封裝百度搜尋方塊元素 """ input_element = '#kw' # 輸入框元素 click_element = '#su' # 點選搜尋元素
""" 前置後置操作:初始化操作 """ from playwright.sync_api import sync_playwright class SetupTeardown: """ 啟動瀏覽器 """ def __init__(self): self.p = sync_playwright().start() # 建立playwright物件 self.browser = self.p.chromium.launch(headless=False, slow_mo=1000) # 啟動谷歌瀏覽器賦值給物件 self.page = self.browser.new_page() # 開啟一個頁面 """ 關閉瀏覽器 """ def close(self): self.browser.close() # 關閉瀏覽器物件 self.p.stop() # 關閉playwright物件釋放資源 """ 截圖操作儲存到result_image目錄下 """ def screenshot(self, element, file_name): self.page.locator(element).screenshot(path=f"../result_image/{file_name}.png")
""" 封裝搜尋頁:初始化定位元素、重寫輸入操作、點選操作,截圖操作 """ from tools.conftest import SetupTeardown class SearchPage(SetupTeardown): """ 封裝定位元素 """ def __init__(self): super().__init__() # 呼叫基礎頁面的建構函式,完成瀏覽器啟動和頁面開啟 """ 去往搜尋頁 """ def navigate(self): self.page.goto('https://www.baidu.com/') """ 輸入操作 """ def input_element(self, element, keyword): self.page.fill(element, keyword) """ 點選操作 """ def click_element(self, element): self.page.click(element) """ 截圖搜尋結果頁 """
""" 搜尋頁的測試用例 """ from element.search_element import * # 匯入搜尋頁的所有定位元素 from page.search_page import SearchPage # 匯入搜尋頁物件 search_page = SearchPage() # 初始化搜尋頁物件 search_page.navigate() # 去往搜尋頁 search_page.input_element(input_search_element, 'playwright') # 搜尋方塊輸入內容 search_page.click_element(click_search_element) # 點選搜尋 search_page.screenshot('result_search_page') # 截圖儲存 search_page.close() # 關閉瀏覽器