1. 程式人生 > >Selenium2+python自動化63-二次封裝(click/send_kesy)

Selenium2+python自動化63-二次封裝(click/send_kesy)

自動 nbsp 自動化 cep hat cond ati 但是 分享

我們學了顯示等待後,就不需要sleep了,然後查找元素方法用參數化去定位,這樣定位方法更靈活了,但是這樣寫起來代碼會很長了,於是問題來了,總不能每次定位一個元素都要寫一大堆代碼吧?這時候就要學會封裝啦

一、顯示等待

1.如果你的定位元素代碼,還是這樣:driver.find_element_by_id("kw").send_keys("yoyo"),那說明你還停留在小學水平,如何讓代碼提升逼格呢?

2.前面講過顯示等待相對於sleep來說更省時間,定位元素更靠譜,不會出現一會正常運行,一會又報錯的情況,所以我們的定位需與WebDriverWait結合

3.以百度的搜索為例

技術分享圖片

二、封裝定位方法

1.從上面代碼看太長了,每次定位寫一大串,這樣不方便閱讀,寫代碼的效率也低,於是我們可以把定位方法進行封裝

2.定位方法封裝後,我們每次調用自己寫的方法就方便多了

技術分享圖片

三、封裝成類

1.我們可以把send_keys()和click()方法也一起封裝,寫到一個類裏

2.定位那裏很多小夥伴弄不清楚lambda這個函數,其實不一定要用這個,我們可以用EC模塊的presence_of_element_located()這個方法,參數直接傳locator就可以了

3.以下是presence_of_element_located這個方法的源碼:

class presence_of_element_located(object):
""" An expectation for checking that an element is present on the DOM
of a page. This does not necessarily mean that the element is visible.
locator - used to find the element
returns the WebElement once it is located
"""
def __init__(self, locator):
self.locator = locator

def __call__(self, driver):
return _find_element(driver, self.locator)

四、參考代碼

1.把get、find_element、click、send_keys封裝成類

# coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import *   # 導入所有的異常類
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class Yoyo(object):
    """基於原生的selenium框架做了二次封裝.
""" def __init__(self): """啟動瀏覽器參數化,默認啟動firefox.""" self.driver = webdriver.Firefox() def get(self, url): ‘‘‘使用get打開url‘‘‘ self.driver.get(url) def find_element(self, locator, timeout=10): ‘‘‘定位元素方法封裝‘‘‘ element = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator)) return element def click(self, locator): ‘‘‘點擊操作‘‘‘ element = self.find_element(locator) element.click() def send_keys(self, locator, text): ‘‘‘發送文本,清空後輸入‘‘‘ element = self.find_element(locator) element.clear() element.send_keys(text) if __name__ == "__main__": d = Yoyo() # 啟動firefox d.get("https://www.baidu.com") input_loc = ("id", "kw") d.send_keys(input_loc, "yoyo") # 輸入搜索內容 button_loc = ("id", "kw") d.click(button_loc) # 點擊搜索按鈕

Selenium2+python自動化63-二次封裝(click/send_kesy)