使用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/attributeDescriptionExample
current_urlThis gets the        URL        of the current page        displayed in the browserdriver.current_url
current_window_handleThis gets the handle of        the        current        windowdriver.current_window_handle
nameThis        gets the name of the underlying        browser        for        this instancedriver.name
orientationThis gets        the        current        orientation        of the devicedriver.orientation
page_sourceThis gets        the        source of the current pagedriver.page_source
titleThis gets the title        of the current pagedriver.title
window_handlesThis gets the        handles        of all windows within the current sessiondriver.window_handles

方法列表:

MethodDescriptionArgumentExample
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        navigatedriver.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 todriver.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/attributeDescriptionExample
sizeThis        gets the size of the elementelement.size
tag_nameThis        gets this element’ s HTML tag nameelement.tag_name
textThis        gets the text of the elementelement.text

方法列表:

MethodDescriptionArgumentExample
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/attributeDescriptionExample
all_selected_optionsThis        gets a list        of all the selected        options        belonging to the dropdown or listselect_element.all_selected_options
first_selected_optionThis gets the first        selected/currently selected        option from        the        dropdown or        listselect_element.first_selected_option
optionsThis gets        a list of all options from the dropdown        or listselect_element.options

方法列表:

MethodDescriptionArgumentExample
deselect_()This clears all the selected entries from        a multiselect dropdown or listselect_element.deselect_() 
deselect_by_index(index)This        deselects the option at        the        given index        from the dropdown or listindex is the index of the option        to        be deselecteddeselect_element.deselect_by_index(1)
deselect_by_value(value)This deselects all options that have a value matching the argument from the dropdown        or listvalue is the        value attribute        of the option to be deselectedselect_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 listtext is the text value of        the        option to be        deselectedselect_element.deselect_by_visible_text(“bar”)
select_by_index(index)This selects an option        at the given index from        the        dropdown or listindex is the index of the option to        be selectedselect_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 listvalue is        the        value attribute        of the option to be        selectedselect_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 listtext is the text value of the option to be        selectedselect_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/attributeDescriptionExample
textThis        gets text from the alert windowalert.text

方法列表:

MethodDescriptionArgumentExample
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 buttonalert.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)

自动化浏览器浏览

MethodDescriptionArgumentExample
back()This goes one step        backward in        the        browser        history        in        the        current session.Nonedriver.back()
forward()This goes one step forward in the browser history in the current session.Nonedriver.forward()
refresh()This refreshes the current page        displayed in the browser.Nonedriver.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被和谐,通常无法执行,仅供参考。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值