自动化测试(3-2):基本API

注意下面例子中的网址url需要安装好apache

  • (1)判断页面元素是否可见is_displayed()
#例子8:判断页面元素是否可见is_displayed()
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_getWebElementIsDisplayed(self):
        # 下面的url是apache安装目录下的html,下面获取元素时可以查看下网页源代码
        url = "http://127.0.0.1/test_visible.html"
        # 访问自定义的html网页
        self.driver.get(url)
        time.sleep(3)
        # 通过id="div2"找到第二个div元素
        div2 = self.driver.find_element_by_id("div2")
        # 判断第二个div元素是否在页面上可见
        print (div2.is_displayed())
        # 点击第一个切换div按钮,将第二个div显示在页面上
        self.driver.find_element_by_id("button1").click()
        time.sleep(3)
        # 再次判断第二个div元素是否在页面上可见
        print (div2.is_displayed())
        # 通过id="div4"找到第四个div元素
        div4 = self.driver.find_element_by_id("div4")
        # 判断第四个div元素是否在页面上可见
        print (div4.is_displayed())
        # 点击第二个切换div按钮,将第四个div显示在页面上
        self.driver.find_element_by_id("button2").click()
        time.sleep(3)
        # 再次判断第四个div元素是否在页面上可见
        print (div4.is_displayed())

    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (2)判断元素是否可操作is_enabled(),并修改本地元素的状态
#例子9:判断元素是否可操作is_enabled(),并修改本地元素的状态
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
       # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_getWebElementIsEnabled(self):
        url = "http://127.0.0.1/test_enable.html"
        # 访问自定义的html网页
        self.driver.get(url)
        # 通过id找到第一个input元素
        input1 = self.driver.find_element_by_id("input1")
        # 判断第一个input元素是否可操作
        print (input1.is_enabled())
        # 通过id找到第二个input元素
        input2 = self.driver.find_element_by_id("input2")
        # 判断第二个input元素是否可操作
        print (input2.is_enabled())
        # 通过id找到第三个input元素
        input3 = self.driver.find_element_by_id("input3")
        # 判断第三个input元素是否可操作(只读也是可操作的)
        print (input3.is_enabled())
        time.sleep(3)

        # 修改本地某个元素的状态为非禁用状态,不会修改服务端这个元素的状态,document是网页的源码(运用w3school里面js的知识点)
        self.driver.execute_script("document.getElementById('input2').disabled=false;")
        # 清空输入框
        input2.clear();
        time.sleep(2)        
        # 在输入框中输入"北京"
        input2.send_keys("北京")
        time.sleep(5)

    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (3)单击按钮click()
#例子11:单击按钮click()
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
       # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_clickButton(self):
        url = "http://127.0.0.1/test_button.html"
        # 访问自定义的html网页
        self.driver.get(url)
        # 获取按钮页面对象
        button = self.driver.find_element_by_id("button")
        # 模拟鼠标左键单击操作
        button.click()    
        time.sleep(3)
      
    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (4)双击元素(需要导入包ActionChains)
#例子12:双击元素(需要另外导入包ActionChains)
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_doubleClick(self):
        url = "http://127.0.0.1/test_doubleclick.html"
        # 访问自定义的html网页
        self.driver.get(url)
        time.sleep(3)
        # 获取页面输入元素
        inputBox = self.driver.find_element_by_id("inputBox") 
        # 导入支持双击操作的模块
        from selenium.webdriver import ActionChains
        # 开始模拟鼠标双击操作inputBox元素(固定用法)
        action_chains = ActionChains(self.driver)
        action_chains.double_click(inputBox).perform()   
        time.sleep(3)

    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (5)选择单选下拉框的选项(两种方法,第二个方法使用的Select模块)
#例子12:选择单选下拉框的选项(两种方法,其中一个方法做了封装)
#方法一:先找下拉框元素,然后根据下拉框元素找所有的选项
import unittest
import time
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_printSelectText(self):
        url = "http://127.0.0.1/test_select.html"
        # 访问自定义的html网页
        self.driver.get(url)
        # 使用name属性找到页面上name属性为"fruit"的下拉列表元素
        select = self.driver.find_element_by_name("fruit")
        #select.click()  #显示出下拉(这里的下拉会一直显示,当选中其他选项时,下拉里面没有显示出动态效果)
        # 使用tag_name属性找到"fruit"下的所有选项
        all_options = select.find_elements_by_tag_name("option")      #注意这里是elements
        for option in all_options:
            #print (u"选项显示的文本:", option.text)
            #print (u"选项值为:", option.get_attribute("value"))
            if option.text =="西瓜":
                option.click()
            time.sleep(1)

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
#===============将方法一的代码做了封装,以后直接调用=====================================================
from selenium import webdriver
import time
def choose_option(driver,select_xpath,option_text):
        '''driver:表示哪个浏览器 
           select_xpath:表示要定位的元素
           option_text:表示元素里的选项文本          
        '''
        # 使用xpath找到页面上属性为select_xpath的下拉列表元素
        select = driver.find_element_by_xpath(select_xpath)
        #select.click()      
        # 使用tag_name属性找到select_xpath下的所有选项option
        all_options = select.find_elements_by_tag_name("option")
        for option in all_options:
            #print (u"选项显示的文本:", option.text)
            #print (u"选项值为:", option.get_attribute("value"))
            if option.text ==option_text:
                option.click()
            time.sleep(1)
driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
url = "http://127.0.0.1/test_select.html"
driver.get(url)
# 调用上面封装的方法
choose_option(driver,"//select[@name='fruit']",'西瓜')
driver.quit()


#方法二:导入一个Select模块(这个比较方便)
#通过Select提供的方法和属性,我们可以对标准select下拉框进行任何操作,但是对于非select标签的伪下拉框,请看第15个例子
'''
1)Select提供了三种选择方法:
  select_by_index(index) ——通过选项的顺序,第一个为0 
  select_by_value(value) ——通过value属性 
  select_by_visible_text(text) ——通过选项可见文本
2)Select提供了四种方法取消选择:
  deselect_by_index(index) 
  deselect_by_value(value) 
  deselect_by_visible_text(text) 
  deselect_all()
3)Select提供了三个属性方法给我们必要的信息:
  options提供所有的选项的列表,其中都是选项的WebElement元素 
  all_selected_options提供所有被选中的选项的列表,其中也均为选项的WebElement元素 
  first_selected_option提供第一个被选中的选项的WebElement元素,也是下拉框的默认值
'''
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_operateDropList(self):
        url = "http://127.0.0.1/test_select.html"
        # 访问自定义的html网页
        self.driver.get(url)

        # 导入Select模块
        from selenium.webdriver.support.ui import Select
        # 使用xpath定位方式获取select页面元素对象
        select = self.driver.find_element_by_xpath("//select")
        #select.click()  # 显示出下拉
        # 实例化Select
        select_element = Select(select)
        # 打印默认选中项的文本,select_element.first_selected_option默认选项
        print ("默认的选项是:%s" %(select_element.first_selected_option.text))
        # 获取所有选择项的页面元素对象
        all_options = select_element.options
        # 打印选项总个数
        print ("所有选项的个数是:%s" %(len(all_options)))
        time.sleep(2)
        '''
        is_enabled():判断元素是否可操作,is_selected():判断元素是否被选中
        '''
        # 方法一:通过序号选中第二个选项'西瓜'
        if all_options[1].is_enabled() and not all_options[1].is_selected():
            # 选中第二个元素,坐标从0开始(选中的值都会自动记录到all_selected_options中)
            select_element.select_by_index(1)
            # 打印已选中项的文本,select_element.all_selected_options[0]表示当前选中的选项(只有一个被选中)
            print ("现在已选中的选项是:%s" %(select_element.all_selected_options[0].text))
            # assertEqual()方法断言当前选中的选项文本是否是"西瓜"
            self.assertEqual(select_element.all_selected_options[0].text, u"西瓜")
            time.sleep(2)
        
        # 方法二:通过选项的显示文本选中text='西瓜'的选项
        if all_options[1].is_enabled() and not all_options[1].is_selected():
            # 选中text值是"西瓜"的选项
            select_element.select_by_visible_text("西瓜")
            # assertEqual()方法断言当前选中的选项文本是否是"西瓜"
            self.assertEqual(select_element.all_selected_options[0].text, u"西瓜")
            time.sleep(2)

        # 方法三:通过选项的value属性值选中value='xigua'的选项
        if all_options[1].is_enabled() and not all_options[1].is_selected():
            # 选中value值是"xigua"的选项
            select_element.select_by_value("xigua")
            # assertEqual()方法断言当前选中的选项文本是否是"西瓜"
            self.assertEqual(select_element.all_selected_options[0].text, u"西瓜")
            time.sleep(2)
        
    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

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


  • (6)选择多选下拉框的选项(使用Select模块选中多个、一个一个的取消选中、一次性全部取消)
#例子13:选择多个选项和取消选项的选中(单个单个的选,一次性全选和一次性取消所有选项的选中、单个取消选项的选中)
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_operateMultipleOptionDropList(self):
        url = "http://127.0.0.1/test_multiple_select.html"
        # 访问自定义的html网页
        self.driver.get(url)

        # 导入Select模块
        from selenium.webdriver.support.ui import Select
        # 使用xpath定位方式获取select页面元素对象
        select = self.driver.find_element_by_xpath("//select")
        # 实例化Select
        select_element = Select(select)
        '''下面是一个一个的选中选项的三种方式'''
        # 通过序号选择第一个元素
        select_element.select_by_index(0)
        # 通过选项的文本选择"山楂"选项
        select_element.select_by_visible_text("山楂")
        # 通过选项的value属性值选择value="mihoutao"的选项
        select_element.select_by_value("mihoutao")
        # 打印所有选中项的文本(前面操作了选择后,会把被选择的元素自动记录到这个变量all_selected_options中)
        for option in select_element.all_selected_options:
            print (option.text)
        time.sleep(3)            
        '''下面是一个一个的取消选项的选中'''
         # 通过序号取消已选中的序号为0的选项
        select_element.deselect_by_index(0)
        # 通过选项文本取消已选中的文本为"山楂"选项
        select_element.deselect_by_visible_text("山楂")        
        # 通过选项的value属性值取消已选中的value="mihoutao"的选项
        select_element.deselect_by_value("mihoutao")
        time.sleep(3)   
        '''下面是通过遍历选中所有的选项'''
        for i in range(len(select_element.options)):
            select_element.select_by_index(i)
        time.sleep(3)
        '''下面是一次性取消所有已选中项'''
        select_element.deselect_all()
        time.sleep(3)
      
    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (7)断言下拉框的选项是不是和期望的一致
#例子14:断言下拉框的选项是不是和期望的一致
import unittest
import time
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        # 启动chrome浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        
    def test_checkSelectText(self):
        url = "http://127.0.0.1/test_select.html"
        # 访问自定义的html网页
        self.driver.get(url)
        time.sleep(3)

        # 导入Select模块
        from selenium.webdriver.support.ui import Select
        # 使用xpath定位方式获取select页面元素对象
        select_element = Select(self.driver.find_element_by_xpath("//select"))
        # 获取所有选择项的页面元素对象
        actual_options = select_element.options
        # 声明一个list对象,存储下拉列表中所期望出现的文字内容
        expect_optionsList = [u"桃子",u"西瓜",u"橘子",u"猕猴桃",u"山楂",u"荔枝"]
        # 使用Python内置map()函数(Python六剑客之一)获取页面中下拉列表展示的选项内容组成的列表对象
        actual_optionsList = list(map(lambda option: option.text, actual_options))
        # 断言期望列表对象和实际列表对象是否完全一致
        self.assertListEqual(expect_optionsList, actual_optionsList)
        # 上面使用的单元测试框架里的断言,也可以直接使用assert expect_optionsList == actual_optionsList进行断言

    def tearDown(self):
        # 退出chrome浏览器
        self.driver.quit()

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

"""list(map(lambda option: option.text, actual_options))可以使用下面的代码替代
option_text_list = []
for option in actual_options:
    option_text_list.append(option.text)
"""

  • (8)操作可以输入的下拉框(需要导入keys包进行选中选项),chrome和火狐不支持,只支持IE
#例子15:操作可以输入的下拉框(需要导入keys包进行选中选项)。chrome和火狐不支持,只支持IE
import unittest
import time
import chardet
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动浏览器
        #self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        #self.driver = webdriver.Firefox(executable_path = "e:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "E:\\IEDriverServer")
        
    def test_operateMultipleOptionDropList(self):
        url = "http://127.0.0.1/test_input_select.html"
        # 访问自定义的html网页
        self.driver.get(url)
        # 导入Keys包
        from selenium.webdriver.common.keys import Keys
        self.driver.find_element_by_id("select").clear()
        # 输入P之后,按两次箭头向下键,一次enter键(执行代码自动进行搜索P,下拉里面只会显示包含P的选项;在页面上访问这个网址,输入P,下拉里面显示包含P和p的选项)
        self.driver.find_element_by_id("select").send_keys("P")
        self.driver.find_element_by_id("select").send_keys( Keys.ARROW_DOWN)
        self.driver.find_element_by_id("select").send_keys( Keys.ARROW_DOWN)
        self.driver.find_element_by_id("select").send_keys( Keys.ENTER)
        time.sleep(3)

    def tearDown(self):
        # 退出浏览器
        self.driver.quit()
		#pass

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

  • (9)操作单选框
#例子16:操作单选框
import unittest
import time
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动浏览器
        self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        #self.driver = webdriver.Firefox(executable_path = "E:\\geckodriver")
        #self.driver = webdriver.Ie(executable_path = "E:\\IEDriverServer")
        
    def test_operateRadio(self):
        url = "http://127.0.0.1/test_radio.html"
        # 访问自定义的html网页
        self.driver.get(url)
        time.sleep(3)
        # 使用xpath定位获取value属性值为'berry'的input元素对象,也就是"草莓"选项
        berryRadio = self.driver.find_element_by_xpath("//input[@value='berry']")
        # 点击选择"草莓"选项
        berryRadio.click()
        time.sleep(2)
        # 断言"草莓"复选框被成功选中
        self.assertTrue(berryRadio.is_selected(), u"草莓复选框未被选中!")
        if berryRadio.is_selected():
            # 如果"草莓"复选框被成功选中,重新选择"西瓜"选项
            watermelonRadio = self.driver.find_element_by_xpath("//input[@value='watermelon']")
            # 点击选择"西瓜"选项
            watermelonRadio.click()
            time.sleep(2)
            # 选择"西瓜"选项以后,断言"草莓"选项处于未被选中状态
            self.assertFalse(berryRadio.is_selected())
            
        # 查找所有name属性值为"fruit"的单选框元素对象,并存放在radioList列表中
        radioList = self.driver.find_elements_by_xpath("//input[@name='fruit']")
        '''
        循环遍历radioList中的每个单选按钮,查找value属性值为"orange"的单选框,
        如果找到此单选框以后,发现处于未选中状态,则调用click方法选中该选项。
        '''
        for radio in radioList:
            if radio.get_attribute("value") == "orange":
                if not radio.is_selected():
                    radio.click()
                    time.sleep(2)
                    self.assertEqual(radio.get_attribute("value"), "orange")
        
    def tearDown(self):
        # 退出浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • (10)操作复选框
#例子17:操作复选框
import unittest
import time
from selenium import webdriver
 
class VisitSogouByIE(unittest.TestCase):

    def setUp(self):
        #启动浏览器
        #self.driver = webdriver.Chrome(executable_path = "E:\\chromedriver")
        #self.driver = webdriver.Firefox(executable_path = "E:\\geckodriver")
        self.driver = webdriver.Ie(executable_path = "E:\\IEDriverServer")
        
    def test_operateCheckBox(self):
        url = "http://127.0.0.1/test_checkbox.html"
        # 访问自定义的html网页
        self.driver.get(url)
        time.sleep(3)
        # 使用xpath定位获取value属性值为'berry'的input元素对象,也就是"草莓"选项
        berryCheckBox = self.driver.find_element_by_xpath("//input[@value='berry']")
        # 点击选择"草莓"选项
        berryCheckBox.click()
        time.sleep(2)
        # 断言"草莓"复选框被成功选中
        self.assertTrue(berryCheckBox.is_selected(), u"草莓复选框未被选中!")
        if berryCheckBox.is_selected():
            # 如果"草莓"复选框被成功选中,再次点击取消选中
            berryCheckBox.click()
            time.sleep(2)
            # 断言"草莓"复选框处于未选中状态
            self.assertFalse(berryCheckBox.is_selected())
        # 查找所有name属性值为"fruit"的复选框元素对象,并存放在checkBoxList列表中
        checkBoxList = self.driver.find_elements_by_xpath("//input[@name='fruit']")
        # 遍历遍历checkBoxList列表中的所有复选框元素,让全部复选框处于被选中状态
        for box in checkBoxList:
            if not box.is_selected():
                box.click()
        time.sleep(3)

    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值