使用Python學習selenium測試工具-5:元素交互

本節主要內容如下:

  • 瞭解更多關於WebDriver和WebElement類的知識

  • 使用webdriver和WebElement類方法和屬性實現測試與應用交互

  • 使用Select類自動化下拉菜單和列表的操作

  • 自動化的JavaScript彈窗和瀏覽器操作。

HTML表單的元素

HTML
--HEAD TITLE
--BODY
----FORM
----INPUT: Text,Password, Submit, Checkbox, Radio, FileEA
----TEXTAREA
----SELECT OPTION
----TABLE: THEAD,TBODY,TR(Rows),TD(columns/cells)
----DIV
----P(Paragraph)
----Headings(H1,H2...)
----A(Anchor)

webDriver類

webDriver類主要用於和瀏覽器交互,完整的屬性和方法參見:selenium.webdriver.remote.webelement

屬性列表:

Property/attribute Description Example
current_url This gets the        URL        of the current page        displayed in the browser driver.current_url
current_window_handle This gets the handle of        the        current        window driver.current_window_handle
name This        gets the name of the underlying        browser        for        this instance driver.name
orientation This gets        the        current        orientation        of the device driver.orientation
page_source This gets        the        source of the current page driver.page_source
title This gets the title        of the current page driver.title
window_handles This gets the        handles        of all windows within the current session driver.window_handles

方法列表:

Method Description Argument Example
back() This goes one step        backward in the        browser        history        in the        current session.   driver.back()
close() This closes the current browser window.   driver.close()
forward() This goes one step forward in the browser history in the current session.   driver.forward()
get(url) This        navigates and loads        a web page in the current browser session. url is the address of the website or web page to        navigate driver.get(“http://www.google.com”)
maximize_window() This maximizes the current browser window.   driver.maximize_window()
quit() This quits        the driver and closes all the associated windows.   driver.quit()
refresh() This refreshes the current page        displayed in the browser.   driver.refresh()
switch_to.active_element() This returns the element with focus or        the        body if        nothing        else has focus.   driver.switch_to_active_element()
Switch.to_alert() This switches the focus        to an alert        on        the        page.   driver.switch_to_alert()
switch_to.default_content() This switches        the        focus to the default frame.   driver.switch_to_default_content()
switch_to.frame(frame_reference) This switches the focus to the specified        frame, by index, name, or web element. This        method also        works on IFRAMES. frame_reference: This is the name of the window to switch        to,        an integer representing        the        index, or a        web        element that is        a frame        to switch to driver.switch_to_frame(‘frame_name’)
switch_to.window(window_name) This switches focus        to the specified window. window_name is the name or window handle of        the window to switch to. driver.switch_to_window(‘main’)
implicitly_wait(time_to_wait) This sets a        sticky timeout to implicitly wait for an element to        be found, or a command to complete.        This method        only needs to be called        one        time        per        session. To         set        the        timeout        for        calls to execute_async_script,        see        set_script_timeout. time_to_wait is        the        amount of time to wait(in seconds).  
set_page_load_timeout(time_to_wait) This        sets the amount        of time to        wait for a page        load to        complete. time_to_wait is the amount of time to wait(in seconds) driver.set_page_load_timeout(30)
set_script_timeout(time_to_wait) This sets the amount of time that the script        should        wait during       an execute_async_script        call before        throwing an error. time_to_wait is the amount of time to wait(in seconds) driver.set_script_timeout(30)

WebElement類

WebElement類主要用於和元素交互,完整的屬性和方法參見:elenium.webdriver.remote.webelement

屬性列表:

Property/attribute Description Example
size This        gets the size of the element element.size
tag_name This        gets this element’ s HTML tag name element.tag_name
text This        gets the text of the element element.text

方法列表:

Method Description Argument Example
clear() This clears the content of the textbox or text area element.   element.clear()
click() This clicks the element.   element.click()
get_attribute(name) This gets the        attribute value        from the element. name is the name of the attribute. element.get_attribute(“value”) Or element.get_attribute(“maxlength”)
is_displayed() This checks whether the element is        visible        to the user.   element.is_displayed()
is_enabled() This        checks        whether        the element is enabled.   element.is_enabled()
is_selected() This checks        whether       the element is selected. This method is        used to check the selection of        a radio        button or checkbox.   element.is_selected()
send_keys(*value) This simulates typing into the element. Value is a string for typing or setting        form fields. element.send_keys(“foo”)
submit() This        submits        a form.        If you call        this method        on an element, it will submit the parent form.   element.submit()
value_of_css_property(property_name) This        gets the value of a        CSS        property. property_name is the name of the CSS property. element.value_of_css_property(“backgroundcolor”)

處理form、textbox、checkbox和radio

下面的homepagetests創建一個用戶,演示了form、textbox、checkbox和radio等操作。

register_new_user.py

from selenium import webdriver
from time import gmtime, strftime
import unittest


class RegisterNewUser(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

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

    def test_register_new_user(self):
        driver = self.driver

        # click on Log In link to open Login page
        driver.find_element_by_link_text('ACCOUNT').click()
        driver.find_element_by_link_text('My Account').click()

        # get the Create Account button
        create_account_button = \
            driver.find_element_by_link_text('CREATE AN ACCOUNT')

        # check Create Account button is displayed and enabled
        self.assertTrue(create_account_button.is_displayed() and
                        create_account_button.is_enabled())

        # click on Create Account button. This will displayed new account
        create_account_button.click()

        # check title
        self.assertEquals('Create New Customer Account', driver.title)

        # get all the fields from Create an Account form
        first_name = driver.find_element_by_id('firstname')
        last_name = driver.find_element_by_id('lastname')
        email_address = driver.find_element_by_id('email_address')
        password = driver.find_element_by_id('password')
        confirm_password = driver.find_element_by_id('confirmation')
        news_letter_subscription = driver.find_element_by_id('is_subscribed')
        submit_button = driver.\
            find_element_by_xpath("//button[@title='Register']")

        # check maxlength of first name and last name textbox
        self.assertEqual('255', first_name.get_attribute('maxlength'))
        self.assertEqual('255', last_name.get_attribute('maxlength'))

        # check all fields are enabled
        self.assertTrue(first_name.is_enabled() and last_name.is_enabled() and
                        email_address.is_enabled() and
                        news_letter_subscription.is_enabled() and
                        password.is_enabled() and confirm_password.is_enabled()
                        and submit_button.is_enabled())

        # check Sign Up for Newsletter is unchecked
        self.assertFalse(news_letter_subscription.is_selected())

        user_name = 'user_' + strftime('%Y%m%d%H%M%S', gmtime())

        # fill out all the fields
        first_name.send_keys('Test')
        last_name.send_keys(user_name)
        news_letter_subscription.click()
        email_address.send_keys(user_name + '@example.com')
        password.send_keys('tester')
        confirm_password.send_keys('tester')

        # click Submit button to submit the form
        submit_button.click()

        # check new user is registered
        self.assertEqual('Hello, Test ' + user_name + '!',
                         driver.find_element_by_css_selector('p.hello > strong').text)
        driver.find_element_by_link_text('ACCOUNT').click()
        self.assertTrue(driver.find_element_by_link_text('Log Out').is_displayed())

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)

執行結果:

test_register_new_user (__main__.RegisterNewUser) ... ok
----------------------------------------------------------------------
Ran 1 test in 133.117s

OK

處理dropdown和list

屬性列表:

Property/attribute Description Example
all_selected_options This        gets a list        of all the selected        options        belonging to the dropdown or list select_element.all_selected_options
first_selected_option This gets the first        selected/currently selected        option from        the        dropdown or        list select_element.first_selected_option
options This gets        a list of all options from the dropdown        or list select_element.options

方法列表:

Method Description Argument Example
deselect_() This clears all the selected entries from        a multiselect dropdown or list select_element.deselect_()  
deselect_by_index(index) This        deselects the option at        the        given index        from the dropdown or list index is the index of the option        to        be deselected deselect_element.deselect_by_index(1)
deselect_by_value(value) This deselects all options that have a value matching the argument from the dropdown        or list value is the        value attribute        of the option to be deselected select_element.deselect_by_value(“foo”)
deselect_by_visible_text(text) This deselects all        the options that display text matching the argument from the dropdown or list text is the text value of        the        option to be        deselected select_element.deselect_by_visible_text(“bar”)
select_by_index(index) This selects an option        at the given index from        the        dropdown or list index is the index of the option to        be selected select_element.select_by_index(1)
select_by_value(value) This selects all the options that have a value matching the argument from the dropdown        or list value is        the        value attribute        of the option to be        selected select_element.select_by_value(“foo”)
select_by_visible_text(text) This         selects        all        the        options        that display the text matching the argument        from the dropdown or list text is the text value of the option to be        selected select_element.select_by_visible_text(“bar”)

代碼文件:homepagetests.py。

from Tkinter import image_names
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import Select


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.assertEqual(2, len(account_links))

    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), 3)

    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)
        self.driver.back()

    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()

    def test_language_options(self):
        # list of expected values in Language dropdown
        exp_options = ["ENGLISH", "FRENCH", "GERMAN"]

        # empty list for capturing actual options displayed in the dropdown
        act_options = []

        # get the Your language dropdown as instance of Select class
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))

        # check number of options in dropdown
        self.assertEqual(3, len(select_language.options))

        # get options in a list
        for option in select_language.options:
            act_options.append(option.text)

        # check expected options list with actual options list
        self.assertListEqual(exp_options, act_options)

        # check default selected option is English
        self.assertEqual("ENGLISH",
                          select_language.first_selected_option.text)

        # select an option using select_by_visible text
        select_language.select_by_visible_text("German")

        # check store is now German
        self.assertTrue("store=german" in self.driver.current_url)

        # changing language will refresh the page,
        # we need to get find language dropdown once again
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))
        select_language.select_by_index(0)

    def test_store_cookie(self):
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))
        select_language.select_by_visible_text("French")
        self.assertEqual("french", self.driver.get_cookie("store")["value"])

        # changing language will refresh the page,
        # we need to get find language dropdown once again
        select_language = \
            Select(self.driver.find_element_by_id("select-language"))
        select_language.select_by_index(0)

    def test_css_for_home_page(self):
        self.assertTrue("demo-logo.png" in
                        self.driver.find_element_by_css_selector("div.notice-inner")
                        .value_of_css_property("background-image"))

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

if __name__ == '__main__':
    unittest.main(verbosity=2)

處理告警和彈出窗口

完整的參考地址:selenium.webdriver.common.alert

屬性列表:

Property/attribute Description Example
text This        gets text from the alert window alert.text

方法列表:

Method Description Argument Example
accept() This        will accept        the        JavaScript? alert.box that is click on the OK button   alert.accept()
dismiss() This will dismiss the JavaScript? alert.box that is click        on the Cancel button alert.dismiss()
send_keys(*value) This simulates typing into the element value is        a string for typing        or setting form        fields   alert.send_keys(“foo”)

實例中先加入商品,然後清空商品,此時會有彈出告警。注意此處的代碼在網速較慢時,彈出窗口可能無法識別,解決方法參見下一章。    

from selenium import webdriver
import unittest


class CompareProducts(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.driver.get('http://demo-store.seleniumacademy.com/')

    def test_compare_products_removal_alert(self):
        # get the search textbox
        search_field = self.driver.find_element_by_name('q')
        search_field.clear()

        # enter search keyword and submit
        search_field.send_keys('phones')
        search_field.submit()

        # click the Add to compare link
        self.driver.\
            find_element_by_link_text('Add to Compare').click()


        # click on Remove this item link,
        # this will display an alert to the user
        self.driver.find_element_by_link_text('Clear All').click()

        # switch to the alert
        alert = self.driver.switch_to.alert

        # get the text from alert
        alert_text = alert.text

        # check alert text
        self.assertEqual('Are you sure you would like to remove all products from your comparison?',
                          alert_text)

        # click on Ok button
        alert.accept()

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)

自動化瀏覽器瀏覽
Method Description Argument Example
back() This goes one step        backward in        the        browser        history        in        the        current session. None driver.back()
forward() This goes one step forward in the browser history in the current session. None driver.forward()
refresh() This refreshes the current page        displayed in the browser. None driver.refresh()

實例: navigation_test.py

import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions


class NavigationTest(unittest.TestCase):
    def setUp(self):
        # create a new Firefox session
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

        # navigate to the application home page
        self.driver.get('http://www.google.com')

    def test_browser_navigation(self):
        driver = self.driver
        # get the search textbox
        search_field = driver.find_element_by_name('q')
        search_field.clear()

        # enter search keyword and submit
        search_field.send_keys('selenium webdriver')
        search_field.submit()

        se_wd_link = driver.\
            find_element_by_link_text('Selenium WebDriver')
        se_wd_link.click()
        self.assertEqual('Selenium WebDriver', driver.title)

        driver.back()
        self.assertTrue(WebDriverWait(self.driver, 10)
            .until(expected_conditions.title_is('selenium webdriver - Google Search')))

        driver.forward()
        self.assertTrue(WebDriverWait(self.driver, 10)
            .until(expected_conditions.title_is('Selenium WebDriver')))

        driver.refresh()
        self.assertTrue(WebDriverWait(self.driver, 10)
            .until(expected_conditions.title_is('Selenium WebDriver')))

    def tearDown(self):
        # close the browser window
        self.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)

上面用例,因爲google被和諧,通常無法執行,僅供參考。

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