美文网首页我爱编程
selenium中常用的下拉框定位Select

selenium中常用的下拉框定位Select

作者: 打五笔的程序员 | 来源:发表于2017-09-14 20:46 被阅读0次

    1.在selenium自动化测试中,我们常常遇到更重下拉框。本文介绍三种常用的下拉框定位方法

    select_by_index(index) 通过索引定位
    select_by_value(value) 通过value值定位
    select_by_visible_text(text) 通过文本内容定位

    2.html 代码如下,大家可以复制一下内容然后保存为select.html格式

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <title>Select选择下拉框演示</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
        #div1{
            height: 202px;
            width: 202px;
            background-color:red;
            margin-left: auto;
            margin-right: auto;
    
        }
        #list{
            height: 150px;
            width: 199px;
            position: relative; 
            margin-left: auto;
            margin-right: auto;
            font: 50px "Microsoft YaHei"; 
        }
    </style>
    </head>
        <body>
            <div id="div1">
                <select id="list" onchange=";" name="listName">
            <option value="1">orange</option>
            <option value="2">peach</option>
            <option value="3">cherry</option>
            <option value="4">mongo</option>
            <option value="5">pear</option>
            <option value="6">grape</option>
            <option value="7">banana</option>
            <option value="8" selected="">lemon</option>
        </select>
        <p id="p1"></p>
            </div>
        </body>
    </html>
    

    3.python定位代码如下

    coding=utf-8
    
    from selenium import webdriver
    from selenium.webdriver.support.select import Select
    import os,time
    
    '''
    处理下拉框
    Select提供了三种方法
    select_by_index(index)
    select_by_value(value)
    select_by_visible_text(text)
    
    '''
    driver=webdriver.Chrome()
    
    file_path='file://'+os.path.abspath('select.html')
    driver.get(file_path)
    
    time.sleep(2)
    
    #先定位到下拉框
    
    se1 = driver.find_element_by_id("list")
    
    #通过索引值来定位 从0开始
    #Select(se1).select_by_index(1)
    
    #通过value属性值等于多少定位
    #Select(se1).select_by_value("1")
    
    #通过文本来定位
    Select(se1).select_by_visible_text('grape')
    
    

    4.这只是一部分select方法,详细的还请看官方api文档

    https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.select.html#module-selenium.webdriver.support.select

    里面详细的介绍了所有的select方法,包括选择,反选等等方法

    相关文章

      网友评论

        本文标题:selenium中常用的下拉框定位Select

        本文链接:https://www.haomeiwen.com/subject/hqhjsxtx.html