IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发工具 -> 第十六:Python+Selenium基础WebdriverApi -> 正文阅读

[开发工具]第十六:Python+Selenium基础WebdriverApi

一.项目目录
在这里插入图片描述
二.各种html文件

1.actionselect.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>操作下拉列表</title>
</head>
<body>
    <select name="fruit" size="1">
        <option id="peach" value="taozi">桃子</option>
        <option id="watermelon" value="xigua">西瓜</option>
        <option id="orange" value="juzi" selected="selected">橘子</option>
        <option id="kiwifruit" value="nihoutao">猕猴桃</option>
        <option id="maybush" value="shanzha">山楂</option>
        <option id="litchi" value="lizhi">荔枝</option>
    </select>
</body>
</html>

2.checkbox.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>操作复选框</title>
</head>
<body>
    <form name="form1">
        <input type="checkbox" name="fruit" value="berry" />草莓</input>
        <input type="checkbox" name="fruit" value="watermelon" />西瓜</input>
        <input type="checkbox" name="fruit" value="orange" />橙子</input>
    </form>
</body>
</html>

3.doubleclick.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模拟鼠标双击操作</title>
</head>
<body>
    <input id="inputBox" type="text" ondblclick="javascript:this.style.background='red'">请双击</>
</body>
</html>

4.inputselect.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>操作可输入下拉列表,输入的同时模拟按键</title>
</head>
<body>
    <div style="position:relative;">
        <input list="pasta" id="select">
        <datalist id="pasta">
            <option>Bavette</option>
            <option>Rigatoni</option>
            <option>Fiorentine</option>
            <option>Gnocchi</option>
            <option>Tagliatelle</option>
            <option>Penne lisce</option>
            <option>Pici</option>
            <option>Pappardelle</option>
            <option>Spaghetti</option>
            <option>Cannelloni</option>
            <option>Cancl</option>
        </datalist>
    </div>
</body>
</html>

5.isdisplay.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML中显示与隐藏元素</title>
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
    <script type="text/javascript">
        function showAndHidden1() {
            var div1 = document.getElementById("div1");
            var div2 = document.getElementById("div2");
            if(div1.style.display=='block') div1.style.display='none';
            else div1.style.display='block';
            if(div2.style.display=='block') div2.style.display='none';
            else div2.style.display='block';

        }
        function showAndHidden2() {
            var div3 = document.getElementById("div3");
            var div4 = document.getElementById("div4");
            if(div3.style.visibility=='visible') div3.style.visibility='hidden';
            else div3.style.visibility='visible';
            if(div4.style.visibility=='visible') div4.style.visibility='hidden';
            else div4.style.visibility='visible';
        }
    </script>
</head>
<body>
    <div>display:元素不占用页面位置</div>
    <div id="div1" style="display: block;">DIV 1</div>
    <div id="div2" style="display: none;">DIV 2</div>
    <input id="button1" type="button" onclick="showAndHidden1();" value="DIV切换" />
    <hr>
    <div>visibility:元素占用页面位置</div>
    <div id="div3" style="visibility: visible;">DIV 1</div>
    <div id="div4" style="visibility: hidden;">DIV 2</div>
    <input id="button2" type="button" onclick="showAndHidden2();" value="DIV切换" />
</body>
</html>

6.isenable.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"/>
    <title>HTML 中不可操作元素</title>
</head>
<body>
    <input id="input1" type="text" size="40" value="可操作">
    <br />
    <input id="input2" type="text" size="40" value="不可用" disabled>
    <br />
    <input id="input3" type="text" size="40" value="只读" readonly>
</body>
</html>

7.multipleOptions.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>操作多选列表</title>
</head>
<body>
    <select name="fruit" size="6" multiple=true>
        <option id="peach" value="taozi">桃子</option>
        <option id="watermelon" value="xigua">西瓜</option>
        <option id="orange" value="juzi">橘子</option>
        <option id="kiwifruit" value="nihoutao">猕猴桃</option>
        <option id="maybush" value="shanzha">山楂</option>
        <option id="litchi" value="lizhi">荔枝</option>
    </select>
</body>
</html>

8.radio.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>操作单选框</title>
</head>
<body>
    <form>
        <input type="radio" name="fruit" value="berry" />草莓</input>
        <br />
        <input type="radio" name="fruit" value="watermelon" />西瓜</input>
         <br />
        <input type="radio" name="fruit" value="orange" />橙子</input>
    </form>
</body>
</html>

9.titleWindow.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用title属性识别和操作新弹出的浏览器窗口</title>

</head>
<body>
    <p id = 'p1'>title属性识别</p>
    <br><br>
    <a href="http://www.sogou.com" target="_blank">sogou 搜索</a>
</body>
</html>

10.uploadfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自动上传文件</title>
</head>
<body>
    <form enctype="multipart/form-data" action="parse_file.jsp" mothod="post">
        <p>Browse for a file to upload:</p>
        <input id="file" name="file" type="file">
        </input>
        <br/><br/>
        <input type="submit" id="filesubmit" value="SUBMIT">
        </input>
    </form>

</body>
</html>

11.frameset.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>frameset 页面</title>
</head>
<frameset cols="25%,50%,25%">
    <frame id="leftframe" src="frame_left.html" />
    <frame id="middleframe" src="frame_middle.html" />
    <frame id="rightframe" src="frame_right.html" />
</frameset>
</html>

二.实例

1.WebdriverApi基础实例

from selenium import webdriver
import unittest
import time


''' 常用webdriverApi详解(基础部分)'''
class MyTest(unittest.TestCase):


    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()


    # 1.访问具体地址
    # 2.获取当前页面url
    # 3.获取当前页面title
    def testOpenBaiduUrl(self):
        '''
        1.访问具体地址
        :return:
        '''
        baseUrl = 'https://www.baidu.com/'
        baseTitle = u'百度一下'
        self.driver.get(baseUrl)

        currTitle = self.driver.title       # 获取当前页面的标题
        self.assertIn(baseTitle, currTitle, msg=u'页面跳转失败')


    def testBackForwardRefresh(self):
        '''
        前进,后退,刷新当前页面
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        baseSogouUrl = 'https://www.sogou.com/'
        self.driver.get(baseBaiduUrl)
        self.driver.get(baseSogouUrl)

        self.driver.back()
        self.assertIn(self.driver.current_url, baseBaiduUrl, msg=u'百度地址访问错误')
        print(self.driver.current_url)

        self.driver.forward()
        self.assertIn(self.driver.current_url, baseSogouUrl, msg=u'搜狗地址访问错误')
        print(self.driver.current_url)

        if self.driver.current_url == baseBaiduUrl:
            self.driver.find_element_by_id('kw').send_keys('baidu')
        else:
            self.driver.find_element_by_id('query').send_keys('sogou')
        self.driver.refresh()


    def testWindow(self):
        '''
        窗口最大化,获取当前窗口的位置,设置当前窗口的位置
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        position = self.driver.get_window_position()        # 获取当前窗口的位置坐标
        print(u'当前窗口的横坐标为{}'.format(position['x']))
        print(u'当前窗口的纵坐标为{}'.format(position['y']))

        self.driver.set_window_position(400, 200)
        print(u'设置后的窗口的位置坐标:{}'.format(self.driver.get_window_position()))
        self.driver.maximize_window()           #窗口最大化


    def testWindowSize(self):
        '''
        获取当前窗口的大小,设置当前窗口的大小
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)

        #获取当前窗口的大小
        windowSize = self.driver.get_window_size('current')
        print(u'当前窗口的宽为{}'.format(windowSize['width']))
        print(u'当前窗口的高为{}'.format(windowSize['height']))

        #设置当前窗口的大小
        self.driver.set_window_size(width=200, height=400, windowHandle='current')
        print(self.driver.get_window_size('current'))


    def testGetBaiduTitle(self):
        '''
        获取页面的title属性值
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        bdTitle = self.driver.title
        print(bdTitle)
        self.assertEqual(bdTitle,u'百度一下,你就知道',msg=u'页面title不正确')


    def testGetBaiduUrlSourceCode(self):
        '''
        获取页面的url和页面源码
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        bdUrl = self.driver.current_url         # 获取当前页面的url地址
        print(bdUrl)
        self.assertEqual(bdUrl,'https://www.baidu.com/',msg=u'当前页面url不正确')

        sourceCode = self.driver.page_source
        print(sourceCode)


    def testGetwindowHandle(self):
        '''
        获取当前页面的句柄,切换窗口
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        self.driver.maximize_window()

        # 获取当前窗口句柄
        current_handle = self.driver.current_window_handle
        print(current_handle)

        #百度搜索框输入selenium并点击百度一下
        self.driver.find_element_by_id('kw').send_keys('selenium')
        self.driver.find_element_by_id('su').click()
        time.sleep(3)
        #点击selenium的百度百科连接
        self.driver.find_element_by_partial_link_text(u'百度百科').click()

        #获取所有窗口的句柄
        all_handles = self.driver.window_handles
        print(all_handles)
        #打印新窗口的句柄
        print(self.driver.window_handles[-1])

        for handle in all_handles:
            # 切换到新的窗口
            if handle != current_handle:
                self.driver.switch_to.window(handle)
                self.driver.find_element_by_link_text(u'元素硒的英文名').click()
                # 返回到原来的窗口
                self.driver.switch_to.window(current_handle)

                sendKeys = self.driver.find_element_by_id('kw')
                sendKeys.clear()
                sendKeys.send_keys('python')


    def testGetElementInfo(self):
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        self.driver.maximize_window()
        element = self.driver.find_element_by_xpath("//a[text()='新闻']")
        print(u'我的tag_name是{},我的text是{},我的size是{}'.format(element.tag_name,element.text,element.size))


    def testGetCssInfo(self):
        '''
        获取元素的css属性值
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        self.driver.maximize_window()
        element = self.driver.find_element_by_id('kw')
        print(element.value_of_css_property('height'))          # 获取搜索框的高
        print(element.value_of_css_property('width'))           # 获取搜索框的宽
        print(element.value_of_css_property('font-family'))     # 获取搜索框输入的字体


    def testInputClear(self):
        '''
        清空输入框数据
        :return:
        '''
        baseBaiduUrl = 'https://www.baidu.com/'
        self.driver.get(baseBaiduUrl)
        self.driver.maximize_window()
        element = self.driver.find_element_by_id('kw')
        element.send_keys('python')     # 输入指定内容
        time.sleep(5)
        element.clear()                 # 清空输入框


    def testElementIsDisplay(self):
        '''
        判断元素是否可见
        :return:
        '''
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/isdisplay.html')
        self.driver.maximize_window()

        # 找到div2元素
        div2 = self.driver.find_element_by_id('div2')
        # 判断div2元素是否可见
        if div2.is_displayed():
            print(u'div2 元素可见')
        else:
            print(u'div2 元素不可见')
        # 点击第一个按钮
        button1 = self.driver.find_element_by_id('button1')
        button1.click()
        # 再次判断div2元素是否可见
        if div2.is_displayed():
            print(u'div2 元素可见')
        else:
            print(u'div2 元素不可见')

        #找到div4元素
        div4 = self.driver.find_element_by_id('div4')
        # 判断div4是否可见
        if div4.is_displayed():
            print(u'div4 元素可见')
        else:
            print(u'div4 元素不可见')
        # 点击第二个按钮
        button2 = self.driver.find_element_by_id('button2')
        button2.click()
        # 再次判断div4元素是否可见
        if div4.is_displayed():
            print(u'div4 元素可见')
        else:
            print(u'div4 元素不可见')


    def testElementIsEnable(self):
        '''
        判断元素是否可操作
        :return:
        '''
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/isenable.html')
        self.driver.maximize_window()

        input1 = self.driver.find_element_by_id('input1')
        if input1.is_enabled():
            print(u'input1 可操作')
        else:
            print(u'input1 不可操作')

        input2 = self.driver.find_element_by_id('input2')
        if input2.is_enabled():
            print(u'input2 可操作')
        else:
            print(u'input2 不可操作')

        input3 = self.driver.find_element_by_id('input3')
        if input3.is_enabled():
            print(u'input3 可操作')
        else:
            print(u'input3 不可操作')


    def testGetAttribute(self):
        '''
        获取元素属性值
        :return:
        '''
        self.driver.get('http://www.sogou.com')
        self.driver.maximize_window()

        query = self.driver.find_element_by_id('query')
        print(query.get_attribute('name'))
        query.send_keys('python')
        print(query.get_attribute('value'))


    def testDoubleClick(self):
        '''
        模拟鼠标双击事件
        :return:
        '''
        from selenium.webdriver import ActionChains         # 模拟鼠标操作事件包
        import time
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/doubleclick.html')
        self.driver.maximize_window()

        # 找到要操作的元素
        time.sleep(3)
        inputbox = self.driver.find_element_by_id('inputBox')
        action = ActionChains(self.driver)
        # 模拟鼠标双击操作
        action.double_click(inputbox).perform()
        time.sleep(3)


    # 遍历下拉列表,获取下拉列表元素的所有显示值和value属性值
    def testSelect(self):
        '''
        操作select下拉列表元素
        :return:
        '''
        import time
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/actionselect.html')
        self.driver.maximize_window()

        # 查找下拉列表元素
        select = self.driver.find_element_by_name('fruit')
        elements = select.find_elements_by_xpath("//option")
        for element in elements:
            print(element.text)
            print(element.get_attribute('value'))
            element.click()
            time.sleep(1)


    def testSelectOption(self):
        import time
        from selenium.webdriver.support.ui import Select
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/actionselect.html')
        self.driver.maximize_window()

        select_element = Select(self.driver.find_element_by_xpath('//select'))
        # 打印默认选项
        print(select_element.first_selected_option.text)
        # 获取所有下拉选项元素
        all_options = select_element.options
        # 打印下拉选项的个数
        print(len(all_options))
        # 如果第二个选项可以操作且没有被选中,那么就选择这个选项
        if all_options[1].is_enabled() and not all_options[1].is_selected():
            # 第一个方法 通过序号选择选项 序号从0开始
            select_element.select_by_index(1)
            # 打印选中选项的文本
            print(select_element.all_selected_options[0].text)
        time.sleep(2)

        # 第二种办法通过选项的文本选择选项
        select_element.select_by_visible_text(u'猕猴桃')
        # 断言选中的选项是否为猕猴桃
        self.assertEqual(select_element.all_selected_options[0].text, u'猕猴桃')    # 3才是索引吧
        time.sleep(2)

        # 第三种方法,通过选项的value属性值选择选项
        select_element.select_by_value('shanzha')
        print(select_element.all_selected_options[0].text)      # 4才是索引吧
        self.assertEqual(select_element.all_selected_options[0].text, u'山楂')


    def testAssertOptions(self):
        from selenium.webdriver.support.ui import Select
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/actionselect.html')
        self.driver.maximize_window()
        select_element = Select(self.driver.find_element_by_xpath('//select'))
        # 找到所有的下拉选项
        actual_options = select_element.options
        print(actual_options)

        # 期望列表
        expect_optionslist = [u'桃子',u'西瓜',u'橘子',u'猕猴桃',u'山楂',u'荔枝']
        # 获取所有的选项的文本值
        actual_optionslist = [actual_options for actual_options in  map(lambda option:option.text, actual_options)]
        print(actual_optionslist)

        # 断言
        self.assertListEqual(expect_optionslist, actual_optionslist)


    def testMultipleOptions(self):
        from selenium.webdriver.support.ui import Select
        import time
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/multipleOptions.html')
        self.driver.maximize_window()
        select_element = Select(self.driver.find_element_by_xpath('//select'))

        print(select_element.all_selected_options)

        # 通过序号选择第一个元素
        select_element.select_by_index(0)
        print(select_element)
        print(select_element.select_by_index(0))

        # 通过文本选择山楂
        select_element.select_by_visible_text(u'山楂')
        print(select_element.select_by_visible_text(u'山楂'))
        # 通过选项的value属性值选择value=猕猴桃
        select_element.select_by_value('nihoutao')
        print(select_element.select_by_value('nihoutao'))

        # 打印所有选中文本
        for option in select_element.all_selected_options:
            print(option.text)

        # 再次选中3个选项
        select_element.select_by_index(1)
        print(select_element.select_by_index(1))
        select_element.select_by_value('juzi')
        print(select_element.select_by_value('juzi'))
        select_element.select_by_visible_text(u'荔枝')
        print(select_element.select_by_visible_text(u'荔枝'))


        print(select_element.deselect_all())

        # 取消3个选项
        select_element.deselect_by_index(0)
        print(select_element.deselect_by_index(0))
        select_element.deselect_by_value('nihoutao')
        print(select_element.deselect_by_value('nihoutao'))
        select_element.deselect_by_visible_text(u'山楂')
        print(select_element.deselect_by_visible_text(u'山楂'))


    def testInputSelect(self):
        from selenium.webdriver.common.keys import Keys
        import time
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/inputselect.html')
        self.driver.maximize_window()
        inputselect = self.driver.find_element_by_id('select')
        # 清空输入下拉框
        inputselect.clear()
        time.sleep(1)
        # 输入的同时按下箭头键
        inputselect.send_keys('c', Keys.ARROW_DOWN)
        time.sleep(1)
        inputselect.send_keys(Keys.ARROW_DOWN)
        time.sleep(1)
        inputselect.send_keys(Keys.ENTER)
        time.sleep(3)


    def testRadio(self):
        import time
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/radio.html')
        self.driver.maximize_window()
        # 定位到草莓选项
        berry = self.driver.find_element_by_xpath("//input[@value='berry']")
        berry.click()
        time.sleep(2)
        # 断言是否被选中
        self.assertTrue(berry.is_selected())

        if berry.is_selected():
            # 如果被选中了重新选择西瓜选项
            watermelon = self.driver.find_element_by_xpath("//input[@value='watermelon']")
            watermelon.click()
            # 断言草莓未被选中
            self.assertFalse(berry.is_selected())

            # 查找一组所有的选项
            options = self.driver.find_elements_by_xpath("//input[@name='fruit']")
            # 遍历所有的选项,如果找到orange且未被选中,那么就选中这项
            for option in options:
                if option.get_attribute('value')=='orange':
                    if not option.is_selected():
                        option.click()


    def testCheckBox(self):
        self.driver.get(r'file:///C:/Users/v-xug/Desktop/checkbox.html')
        self.driver.maximize_window()
        # 选中一个选项并取消
        berry = self.driver.find_element_by_xpath("//input[@value='berry']")
        berry.click()
        # 断言是否被选中
        self.assertTrue(berry.is_selected())
        # 取消选中:如果被选中,在点击一次取消选中
        if berry.is_selected():
            berry.click()

        # 遍历所有的选项并选中所有的选项
        options = self.driver.find_elements_by_xpath("//input[@name='fruit']")
        for option in options:
            if not option.is_selected():
                option.click()


    def testAssertIn(self):
        import time
        self.driver.get('http://www.baidu.com')
        self.driver.maximize_window()
        self.driver.find_element_by_id('kw').send_keys(u'linux超')
        self.driver.find_element_by_id('su').click()
        time.sleep(4)
        self.assertIn(u'linux超', self.driver.page_source, msg=u'页面源码中不存在该关键字')


    def testScreenShot(self):
        '''
        页面截图操作
        :return:
        '''
        self.driver.get('http://www.baidu.com')
        self.driver.maximize_window()
        try:
            # 使用get_screenshot_as_file(filename)方法,对浏览器当前打开的页面截图,并保存在当前目录下
            self.driver.get_screenshot_as_file('baidu.png')
        except IOError as e:
            print(e)


    def testDragDrop(self):
        '''
        模拟鼠标拖拽
        :return:
        '''
        import time
        from selenium.webdriver import ActionChains

        self.driver.get(r'http://jqueryui.com/resources/demos/draggable/scroll.html')
        self.driver.maximize_window()

        element1 = self.driver.find_element_by_id('draggable')
        element2 = self.driver.find_element_by_id('draggable2')
        element3 = self.driver.find_element_by_id('draggable3')

        action = ActionChains(self.driver)
        # 把第一个元素拖拽到第二个元素的位置
        action.drag_and_drop(element1, element2).perform()

        # 把第三个元素拖拽10个像素,拖拽2次
        for i in range(2):
            action.drag_and_drop_by_offset(element3,10,10).perform()
            time.sleep(2)
        action.release()


    def testSingleKey(self):
        import time
        from selenium.webdriver.common.keys import Keys

        self.driver.get('http://www.sogou.com')
        self.driver.maximize_window()

        query = self.driver.find_element_by_id('query')
        # 导入模拟按键模块,输入框发送一个f12按键
        query.send_keys(Keys.F12)
        time.sleep(2)
        # 输入框中输入搜索内容并按下回车键
        query.send_keys('selenium')
        query.send_keys(Keys.ENTER)
        time.sleep(2)


    def testSimulationCombinationKeys(self):
        '''
        模拟组合按键
        :return:
        '''
        from selenium.webdriver import ActionChains
        from selenium.webdriver.common.keys import Keys
        import time

        url = 'http://www.baidu.com'
        self.driver.get(url)
        self.driver.maximize_window()

        # 定位输入框
        input = self.driver.find_element_by_id('kw')
        input.send_keys('python')
        time.sleep(2)
        ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
        time.sleep(2)
        ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
        time.sleep(2)
        self.driver.refresh()
        time.sleep(2)
        ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()
        time.sleep(1)
        self.driver.find_element_by_id('su').click()


    def testSimulationLeftClickMouseOfprocess(self):
        '''
        模拟鼠标左键按下与释放
        鼠标左键点击百度首页的新闻(新闻左键点击不放会变为蓝色)
        :return:
        '''
        from selenium.webdriver import ActionChains
        import time

        url = 'http://www.baidu.com'
        self.driver.get(url)
        self.driver.maximize_window()

        element = self.driver.find_element_by_link_text(u'新闻')
        # 按下鼠标左键并保持不动
        ActionChains(self.driver).click_and_hold(element).perform()
        time.sleep(2)
        #释放鼠标左键
        ActionChains(self.driver).release(element).perform()
        time.sleep(2)


    def testMouseOnElement(self):
        '''
        鼠标悬停在某个元素上
        :return:
        '''
        from selenium.webdriver import ActionChains
        import time

        url = 'http://www.baidu.com'
        self.driver.get(url)
        self.driver.maximize_window()

        newInfo = self.driver.find_element_by_link_text(u'新闻')
        hao123 = self.driver.find_element_by_link_text('hao123')

        action = ActionChains(self.driver)
        action.move_to_element(newInfo).perform()
        time.sleep(2)
        action.move_to_element(hao123).perform()


    #判断元素是否存在
    def isElementpresent(self,*element):
        from selenium.common.exceptions import NoSuchElementException

        try:
            self.driver.find_element(*element)
        except NoSuchElementException as e:
            print(e)
            return False
        else:
            return True

    def testIselementPresent(self):
        url = 'http://www.sogou.com'
        element = ('id', 'query')
        self.driver.get(url)

        ret = self.isElementpresent(*element)
        if ret is True:
            print(u'元素存在')
        else:
            print(u'元素不存在')


    #通过title属性识别和操作新弹出窗口的浏览器窗口
    def testTitleWindow(self):
        from selenium.common.exceptions import NoSuchElementException, TimeoutException
        import time

        url = 'file:///C:/Users/v-xug/Desktop/titleWindow.html'
        self.driver.get(url)

        sogou = self.driver.find_element_by_link_text(u'sogou 搜索')
        sogou.click()
        time.sleep(3)
        # 获取所有的窗口句柄
        all_handles = self.driver.window_handles
        # 打印当前窗口的句柄
        print(self.driver.current_window_handle)
        # 打印所有的窗口句柄
        print(len(all_handles))
        if len(all_handles) > 0:
            try:
                # 遍历每一个窗口:判断新窗口并切换到新窗口
                for windowhandl in all_handles:
                    self.driver.switch_to.window(windowhandl)
                    # 每一个窗口的标题:打印出切换后新窗口的title
                    print(u'窗口',self.driver.title)

                    if self.driver.title == u'搜狗搜索引擎 - 上网从搜狗开始':
                        inputBox = self.driver.find_element_by_id('query')
                        inputBox.send_keys('python')
                    time.sleep(2)
            except NoSuchElementException as e:
                print(e)
            except TimeoutException as e:
                print(e)
        # 切回原来窗口,并打印窗口title
        self.driver.switch_to.window(all_handles[0])
        print(self.driver.title)
        self.assertEqual(self.driver.title, u'使用title属性识别和操作新弹出的浏览器窗口')


    def testHandleFrame(self):
        '''
        操作frame中的页面元素
        :return:
        '''
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.common.exceptions import TimeoutException

        self.driver.get(r'file:///C:/Users/v-xug/Desktop/frameset.html')

        self.driver.switch_to.frame(0)      # 切换到第一个frame中
        left_ele_text = self.driver.find_element_by_xpath('//p')
        leftText = left_ele_text.text       # 打印出文本
        print(leftText)
        self.assertEqual(leftText, u'这是左侧frame页面上的文字')

        # 第一个frame中的按钮
        button = self.driver.find_element_by_tag_name('input')
        button.click()

        try:
            # aler弹窗处理
            alert = WebDriverWait(self.driver, 10).until(EC.alert_is_present())
            # 输出弹窗文本
            print(alert.text)
            alert.accept()
        except TimeoutException as e:
            print(e)

        self.driver.switch_to.default_content()         # 跳到默认的frame,返回最外层
        self.driver.switch_to.frame(1)                  # 跳到第二个frame中
        middle_ele = self.driver.find_element_by_xpath('//p')
        print(middle_ele.text)
        self.assertEqual(middle_ele.text, u'这是中间frame页面上的文字')

        middle_input = self.driver.find_element_by_tag_name('input')
        middle_input.send_keys('python')
        self.driver.switch_to.default_content()


    def testHandleCookie(self):
        '''
        操作页面的cookie信息
        :return:
        '''
        self.driver.get('https://www.sogou.com/')

        # 获取当前页面的所有cookie信息
        cookies = self.driver.get_cookies()
        print(cookies)

        for cookie in cookies:
            print('%s->%s->%s->%s->%s'%(cookie['domain'],cookie['name'], cookie['value'],cookie['expiry'],cookie['path']))

        # 获取name为suv的cookie信息
        ck = self.driver.get_cookie('SUV')
        print('%s->%s->%s->%s->%s' % (ck['domain'], ck['name'], ck['value'], ck['expiry'], ck['path']))

        # 删除name为abtest的cookie信息
        print(self.driver.delete_cookie('ABTEST'))

        # 删除所有的cookie信息
        self.driver.delete_all_cookies()
        print(self.driver.get_cookies())

        # 添加自定义cookie信息
        self.driver.add_cookie({'name':'gloryroadTrain','value':'1479697159269020'})
        # 查看cookie信息
        print(self.driver.get_cookie('gloryroadTrain'))


    def testSetLoadPageTimeOut(self):
        '''
        指定页面加载时间
        :return:
        '''
        import time
        from selenium.common.exceptions import TimeoutException
        from selenium.webdriver.common.keys import Keys

        self.driver.set_page_load_timeout(10)
        try:
            starttime = time.time()
            self.driver.get('https://mail.126.com')
        except TimeoutException:
            print(u'页面加载超时')
            # js语法
            self.driver.execute_script('window.stop()')

        end = time.time() - starttime
        print(end)

        self.driver.switch_to.frame(self.driver.find_element_by_xpath("//div[@id='loginDiv']/iframe"))
        time.sleep(2)
        username = self.driver.find_element_by_xpath("//input[@name='email']")
        username.send_keys('281754043')
        time.sleep(2)
        password = self.driver.find_element_by_xpath("//input[@name='password']")
        password.send_keys('xiaochao11520')
        password.send_keys(Keys.ENTER)


    def test_AjaxBykeys(self):
        '''
        在ajax方式产生的悬浮框中,单击选择包含某个关键字的选项
        :return:
        '''
        from selenium.webdriver.common.keys import Keys
        import time

        self.driver.get('https://www.sogou.com')

        query = self.driver.find_element_by_xpath("//input[@id='query']")
        query.send_keys('python')
        time.sleep(2)
        # 向下选择第三个选项
        for i in range(3):
            query.send_keys(Keys.DOWN)
            time.sleep(1)
        query.send_keys(Keys.ENTER)


    def test_killWindowProcess(self):
        import os

        self.driver.get('http://www.baidu.com')

        recode = os.system('taskkill /iM firefox.exe /F')       # 会结束所有一打开的浏览器的进程
        if recode == 0:
            print(u'结束Chrome进程成功')
        else:
            print(u'结束浏览器进程失败')


    # 上传文件操作(#使用第三方工具autoit上传文件(网上资料很多,不再叙述))
    def test_uploadfile(self):
        import time

        self.driver.get('file:///C:/Users/v-xug/Desktop/fileupload.html')

        upload = self.driver.find_element_by_id('file')
        upload.send_keys(r'D:\mygithub\WebdriverAPI\test.py')
        time.sleep(5)

        submit = self.driver.find_element_by_id('filesubmit')
        submit.click()


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





if __name__ == '__main__':
    #suite = unittest.TestSuite()
    #suite.addTest(MyTest('testMultipleOptions'))
    #runner = unittest.TextTestRunner()
    #runner.run(suite)
    unittest.main()


三.实例二

1.操作富文本框实例:通过js发送正文

    
from selenium import webdriver
import unittest
import time


''' 常用webdriverApi详解(基础部分)'''
class MyTest(unittest.TestCase):


    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()


    # 操作富文本框实例2:通过js发送正文
    def test_SohuSendMail(self):
        import time
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.common.exceptions import TimeoutException, NoSuchWindowException
        from selenium.webdriver.common.by import By
        # 模拟:通过ActionChains(两种都可以)
        from selenium.webdriver import ActionChains
        from selenium.webdriver.common.action_chains import ActionChains


        url = 'http://mail.sohu.com'
        self.driver.get(url)
        time.sleep(2)

        try:
            username = self.driver.find_element_by_xpath("//input[@placeholder='请输入您的邮箱']")
            username.send_keys('13691579846@sohu.com')      # 17707015066@sohu.com
            password = self.driver.find_element_by_xpath("//input[@placeholder='请输入您的密码']")
            password.send_keys('xiaochao11520')             # hyq333888
            commitBtn = self.driver.find_element_by_xpath("//input[@type='submit']")
            commitBtn.click()
            #time.sleep(3)


            # 显示等待,确保登录成功且跳转到成功后的页面
            '''判断某个元素中是否可见并且是enable的,代表可点击'''
            wait = WebDriverWait(self.driver, 5)
            wait.until(EC.element_to_be_clickable((By.XPATH, "//li[text()='写邮件']"))).click()
            #writeMail = self.driver.find_element_by_xpath("//li[text()='写邮件']")
            #writeMail.click()
            time.sleep(5)


            # 正常情况下没有失去焦点,正常输入框输入
            #revicer = self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")
            #revicer.send_keys('281754043@qq.com')


            # 第一种模拟(元素输入时候无法聚焦元素,文本框可以点击,但是send_keys失败)
            '''
            WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//div[@arr='mail.to_render']"))).click()
            ActionChains(self.driver).click(self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")).send_keys('281754043@qq.com').perform()
            '''


            # 第二种模拟(元素输入时候无法聚焦元素,文本框可以点击,但是send_keys失败)
            '''
            WebDriverWait(self.driver,15,0.5).until(EC.visibility_of_element_located((By.XPATH,"//div[@arr='mail.to_render']"))).click()
            ActionChains(self.driver).click(self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")).send_keys(u"413950612@qq.com").perform()
            '''


            # 第三种模拟(元素输入时候无法聚焦元素,文本框可以点击,但是send_keys失败)
            name = self.driver.find_element_by_xpath("//div[@arr='mail.to_render']")
            action = ActionChains(self.driver)
            action.move_to_element(name)
            action.click(name)      # 先点击输入框
            action.send_keys(u"413950612@qq.com")       # 在输入文本框
            action.perform()        # 这个一定要的perform()方法(只有使用了perform方法才会输入进去)



            # 第四种模拟(元素输入时候无法聚焦元素,文本框可以点击,但是send_keys失败)
            '''
            name = self.driver.find_element_by_xpath("//div[@arr='mail.to_render']").click()
            actions = ActionChains(self.driver).move_to_element(name)
            actions.send_keys(u"413950612@qq.com")       # 在输入文本框
            actions.perform()        # 这个一定要的perform()方法(只有使用了perform方法才会输入进去)
            '''



            self.driver.find_element_by_xpath("//body/div[@id='mailContent']/div[1]/div[1]/div[1]/div[4]/input[1]").clear()

            subject = self.driver.find_element_by_xpath("//body/div[@id='mailContent']/div[1]/div[1]/div[1]/div[4]/input[1]")
            subject.send_keys(u'测试邮件')

            #action = ActionChains(self.driver)
            #action.move_to_element(subject)
            #action.click(subject)
            #action.send_keys(u"测试邮件")
            #action.perform()        # 这个一定要的
            time.sleep(2)



            ifram = self.driver.find_element_by_xpath("//iframe[contains(@id,'ueditor_0')]")
            self.driver.switch_to.frame(ifram)

            # 使用js语法在邮件正文输入文本值
            self.driver.execute_script("document.getElementsByTagName('body')[0].innerHTML='<b>邮件正文内容<b>'")
            # 邮件的正文是一个iframe,先切换到这个iframe中,然后直接定位这个iframe中的body元素(’/html/body’)
            #text = self.driver.find_element_by_xpath("/html/body")
            #text = self.driver.find_element_by_xpath("/html[1]/body[1]")
            #text.send_keys('邮件正文')
            time.sleep(2)

            # 上面switch_to.frame()方法就是从原本的主层定位到嵌套层里,就能定位到嵌套层里的元素;
            # 但是呢,使用完上面的方法后,就无法定位到原来主层元素,那就得使用switch_to.default_content()方法,就可以回退到主层了。
            self.driver.switch_to.default_content()
            time.sleep(2)

            send = self.driver.find_element_by_xpath("//span[text()='发送']")
            send.click()
            time.sleep(2)


            # 显示等待发送成功的字样出现
            '''判断某个元素是否被添加到了dom里并且可见,可见代表元素可显示且宽和高都大于0'''
            #wait.until(EC.visibility_of_element_located((By.XPATH, "//span[. ='发送成功']")))
            '''判断元素是否可见,如果可见就返回这个元素'''
            #wait.until(EC.visibility_of(self.driver.find_element(by=By.XPATH,value='//span[. ="发送成功"]')))
            '''判断某个元素是否被加到了dom树里,并不代表该元素一定可见,如果定位到就返回WebElement'''
            #wait.until(EC.presence_of_element_located((By.XPATH, "//span[. ='发送成功']")))
            result = self.driver.find_element_by_xpath("//span[contains(text(),'发送成功')]").text
            print(result)
            self.assertEqual(u'发送成功', result)
        except TimeoutException as e:
            raise
        except NoSuchWindowException as e:
            #print('页面元素不存在', traceback.print_exc())
            raise e
        except Exception as e:
            #print(traceback.print_exc())
            raise e
        
    def tearDown(self):
        #self.driver.quit()
        pass
    
    
if __name__ == '__main__':
    #suite = unittest.TestSuite()
    #suite.addTest(MyTest('testMultipleOptions'))
    #runner = unittest.TextTestRunner()
    #runner.run(suite)
    unittest.main()
  开发工具 最新文章
Postman接口测试之Mock快速入门
ASCII码空格替换查表_最全ASCII码对照表0-2
如何使用 ssh 建立 socks 代理
Typora配合PicGo阿里云图床配置
SoapUI、Jmeter、Postman三种接口测试工具的
github用相对路径显示图片_GitHub 中 readm
Windows编译g2o及其g2o viewer
解决jupyter notebook无法连接/ jupyter连接
Git恢复到之前版本
VScode常用快捷键
上一篇文章           查看所有文章
加:2022-06-18 23:31:51  更:2022-06-18 23:32:01 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/25 6:35:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码