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

來源:互聯網
上載者:User

標籤:find   搜尋   問題   Once   自動化   def   ==   lambda   cal   

我們學了顯示等待後,就不需要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-8from selenium import webdriverfrom selenium.common.exceptions import *   # 匯入所有的異常類from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWaitclass 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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.