使用Python學習selenium測試工具-4:查找元素

web通常包含了Hyper Text Markup Language (HTML)、Cascading Style Sheets (CSS)和JavaScript。本節主要內容如下:

  • 瞭解更多Selenium webDriver查找元素的知識

  • 使用各種瀏覽器提供的開發工具找到和定位元素

  • 多種發現元素的方法:ID、Name、類屬性值、XPath、CSS選擇器

  • Selenium webDriver中的各種find_element_by方法。

一般的瀏覽器都有查看源碼的功能 。

使用開發工具發現定位器

Firefox的插件Firebug是個好幫手,可以F12或者右鍵點擊元素選擇“Inspect Element with Firebug”打開。Firefox的搜素框還可以對XPath或CSS進行查找。

Chrome中可以F12或者右鍵點擊元素選擇“Inspect Element”的方式查看代碼。查找功能也和Firefox類似。Internet Explorer也有類似功能,不再贅述。

元素查找

find_element_by*系列方法在找到元素的時候返回WebElement實例,否則產生NoSuchElementException異常。另外find_elements_by*系列方法可以一次返回多個元素。

driver.find_element_by_css_selector(‘#search’)

Method Description Argument Example
find_element_by_id(id) This method finds an element by the ID attribute value id: The ID of the element to be found driver.find_element_by_id(‘search’)
find_element_by_name(name) This method finds an element by the name attribute value name: The name of the element to be found driver.find_element_by_name(‘q’)
find_element_by_class_name(name) This method finds an element by the class attribute value name: The class name of the element to be found driver.find_element_by_class_name(‘input-text’)
find_element_by_tag_name(name) This method finds an element by its tag name name: The tag name of the element to be found driver.find_element_by_tag_name(‘input’)
find_element_by_xpath(xpath) This method finds an element using XPath xpath: The xpath of the element to be found driver.find_element_by_xpath(‘form[0]/div[0]/input[0]’)
find_element_by_css_selector(css_selector) This method finds an element by the CSS selector css_selector: The CSS selector of the element to be found  
       
find_element_by_link_text(link_text) This method finds an element by the link text link_text: The text of the element to be found driver.find_element_by_link_text(‘Log In’)
find_element_by_partial_link_text(link_text) This method finds an element by a partial match of its link text link_text: The text to match part of the text of the element driver.find_element_by_partial_link_text(‘Log’)

通過id、name、類屬性是最建議,也是最快速的查找方法,尤其是id和name。其次使用tag和鏈接文本,萬不得已才使用xpath和css。

XPath即爲XML路徑語言(XML Path Language),它是一種用來確定XML文檔中某部分位置的語言。參考:XPath維基百科介紹 以及w3schools的Xpath介紹zvon的XPath 1.0介紹。參考書籍:Selenium Testing Tools        Cookbook。注意XPath的速度會比CSS還慢,不過支持向前向後定義和相對路徑。

層疊樣式表(英語:Cascading Style Sheets,簡寫CSS),又稱串樣式列表、層次結構式樣式表文件,一種用來爲結構化文檔(如HTML文檔或XML應用)添加樣式(字體、間距和顏色等)的計算機語言。參考CSS維基百科介紹w3schools之CSS介紹

實例

import unittest
from selenium import webdriver

class HomePageTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # create a new Firefox session
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()

        # navigate to the application home page
        cls.driver.get('http://demo-store.seleniumacademy.com/')

    def test_search_text_field_max_length(self):
        # get the search textbox
        search_field = self.driver.find_element_by_id('search')

        # check maxlength attribute is set to 128
        self.assertEqual('128', search_field.get_attribute('maxlength'))

    def test_search_button_enabled(self):
        # get Search button
        search_button = self.driver.find_element_by_class_name('button')

        # check Search button is enabled
        self.assertTrue(search_button.is_enabled())

    def test_my_account_link_is_displayed(self):
        # get the Account link
        account_link = self.driver.find_element_by_link_text('ACCOUNT')

        # check My Account link is displayed/visible in the Home page footer
        self.assertTrue(account_link.is_displayed())

    def test_account_links(self):
        # get the all the links with Account text in it
        account_links = self.driver.\
            find_elements_by_partial_link_text('ACCOUNT')

        # check Account and My Account link is displayed/visible in the Home page footer
        self.assertTrue(len(account_links), 2)

    def test_count_of_promo_banners_images(self):
        # get promo banner list
        banner_list = self.driver.find_element_by_class_name('promos')

        # get images from the banner_list
        banners = banner_list.find_elements_by_tag_name('img')

        # check there are 3 banners displayed on the page
        self.assertEqual(3, len(banners))

    def test_vip_promo(self):
        # get vip promo image
        vip_promo = self.driver.\
            find_element_by_xpath("//img[@alt='Shop Private Sales - Members Only']")

        # check vip promo logo is displayed on home page
        self.assertTrue(vip_promo.is_displayed())
        # click on vip promo images to open the page
        vip_promo.click()
        # check page title
        self.assertEqual("VIP", self.driver.title)

    def test_shopping_cart_status(self):
        # check content of My Shopping Cart block on Home page
        # get the Shopping cart icon and click to open the Shopping Cart section
        shopping_cart_icon = self.driver.\
            find_element_by_css_selector('div.header-minicart span.icon')
        shopping_cart_icon.click()

        # get the shopping cart status
        shopping_cart_status = self.driver.\
            find_element_by_css_selector('p.empty').text
        self.assertEqual('You have no items in your shopping cart.',
                          shopping_cart_status)
        # close the shopping cart section
        close_button = self.driver.\
            find_element_by_css_selector('div.minicart-wrapper a.close')
        close_button.click()

    @classmethod
    def tearDownClass(cls):
        # close the browser window
        cls.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)
執行結果:

# python        homepagetest.py
test_account_links (__main__.HomePageTest) ... ok
test_count_of_promo_banners_images (__main__.HomePageTest) ... ok
test_my_account_link_is_displayed (__main__.HomePageTest) ... ok
test_search_button_enabled (__main__.HomePageTest) ... ok
test_search_text_field_max_length (__main__.HomePageTest) ... ok
test_shopping_cart_status (__main__.HomePageTest) ... ok
test_vip_promo (__main__.HomePageTest) ... ok
----------------------------------------------------------------------
Ran 7 tests in 77.086s

OK

發佈了28 篇原創文章 · 獲贊 21 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章