首頁 > 軟體

Python selenium find_element()範例詳解

2022-07-08 14:05:17

selenium有以下定位方式:

driver.find_element_by_id(‘id')
driver.find_element_by_xpath('xpath')
driver.find_element_by_link_text('link_text')
driver.find_element_by_partial_link_text('partial_link_text')
driver.find_element_by_name('name')
driver.find_element_by_tag_name('tag_name')
driver.find_element_by_class_name('class_name')
driver.find_element_by_css_selector('css_selector')

但我們看下原始碼:

D:Program FilesPython27Libsite-packagesseleniumwebdriverremotewebdriver.py

可以看到,上面那些定位方式,實際上都是呼叫的driver.find_element(by, value)

我們繼續看下find_element()的原始碼,大部分方法最終全是通過By.CSS_SELECTOR來實現的查詢

那By又都有哪些條件呢?

D:Program FilesPython27Libsite-packagesseleniumwebdrivercommonby.py

繼續看原始碼,可以看到下面8種

ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"

所以我們以後就都只用find_element()就好了,因為最終實際上也都是呼叫的這個方法。

簡單封裝一下,以後就記住find_element()一個方法即可。

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from appium import webdriver

class BasePage(object):
    def split_locator(self, locator):
        """
        分解定位表示式,如'css,.username',拆分後返回'css selector'和定位表示式'.username'(class為username的元素)
        :param locator: 定位方法+定位表示式組合字串,如'css,.username'
        :return: locator_dict[by], value:返回定位方式和定位表示式
        """
        by = locator.split(',')[0]
        value = locator.split(',')[1]
        locator_dict = {
            'id': 'id',
            'name': 'name',
            'class': 'class name',
            'tag': 'tag name',
            'link': 'link text',
            'plink': 'partial link text',
            'xpath': 'xpath',
            'css': 'css selector',
        }
        if by not in locator_dict.keys():
            raise NameError("wrong locator!'id','name','class','tag','link','plink','xpath','css',exp:'id,username'")
        return locator_dict[by], value


    def wait_element(self, locator, sec=30):
        """
        等待元素出現
        :param locator: 定位方法+定位表示式組合字串,用逗號分隔,如'css,.username'
        :param sec:等待秒數
        """
        by, value = self.split_locator(locator)
        try:
            WebDriverWait(self.driver, sec, 1).until(lambda x: x.find_element(by=by, value=value),message='element not found!!!')
            log.info(u'等待元素:%s' % locator)
        return True
        except TimeoutException:
            return False
        except Exception, e:
            raise e

    
    def get_element(self, locator, sec=60):
        """
        獲取一個元素
        :param locator: 定位方法+定位表示式組合字串,用逗號分隔,如'css,.username'
        :param sec:等待秒數
        :return: 元素可找到返回element物件,否則返回False
        """
        if self.wait_element(locator, sec):
            by, value = self.split_locator(locator)
            try:
                element = self.driver.find_element(by=by, value=value)
                log.info(u'獲取元素:%s' % locator)
                return element
            except Exception, e:
                raise e
        else:
            return False

    def get_elements(self, locator):
        """
        獲取一組元素
        :param locator: 定位方法+定位表示式組合字串,用逗號分隔,如'css,.username'
        :return: elements
        """
        by, value = self.split_locator(locator)
        try:
            elements = WebDriverWait(self.driver, 60, 1).until(lambda x: x.find_elements(by=by, value=value))
            log.info(u'獲取元素列表:%s' % locator)
            return elements
        except Exception, e:
            raise e

以後呼叫,先定義元素,如

button = "id,su" # 頁面上id為su的元素

在用例中查詢時,只要寫

find_element(button)

整體框架原始碼:

https://github.com/songzhenhua/selenium_ui_auto/blob/master/page_object/base_page.py

總結

到此這篇關於Python selenium find_element()詳解的文章就介紹到這了,更多相關selenium find_element()詳解內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com