• 吾八哥学Selenium(三):操作复选框checkbox/单选框radio的方法


    复选框checkbox和单选框radio是web网站里经常会使用到的两个控件,那么在web自动化测试的时候如何利用Selenium来操作这俩控件呢?今天我们就来简单入门练习一下!

    html测试页面代码如下:

    <html>
     <head> 
      <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 
      <title>学Python网 - selenium学习测试页面</title> 
     </head> 
     <body> 
      <h2>请选择你喜欢的开发语言</h2> 
      <form> 
       <p><input type="checkbox" id="c1" />C/C++</p>
       <p><input type="checkbox" id="c2" />Java</p>
       <p><input type="checkbox" id="c3" />Python</p>
       <p><input type="checkbox" id="c4" />PHP</p>
       <p><input type="checkbox" id="c5" />Golang</p>
      </form> 
      <h2>您是否喜欢您现在的工作?</h2> 
      <form> 
       <p><input type="radio" name="lovework" value="love" id="rlove" />喜欢</p>
       <p><input type="radio" name="lovework" value="hate" id="rhate" />不喜欢</p>
       <p><input type="radio" name="lovework" value="none" id="rnone" />无所谓</p>
      </form>  
     </body>
    </html>

    从HTML代码看,这里面的复选框checkbox和单选框radio都是input标签,那么我们可以遍历出所有的input标签元素了,而且这些元素也都有id,所以find_element_by_id和find_element_by_xpath操作单个元素也都是可行的。

    Python代码练习:

    # Autor: 5bug
    # WebSite: http://www.XuePython.wang
    # 学Python网QQ群: 643829693
    from selenium import webdriver
    
    driver = webdriver.Chrome("C:/Users/5bug/AppData/Local/Google/Chrome/Application/chromedriver.exe")
    driver.maximize_window()
    driver.get('file:///E:MyCodesPythondemosXuePython.wanghtmlcheck_radio.html')
    
    #遍历得到checkbox/radio,并勾选指定的checkbox/radio
    inputs = driver.find_elements_by_tag_name("input")
    for input in inputs:
        # 读取元素id
        attr_id = input.get_attribute("id")
        print(attr_id)
        element_type = input.get_attribute("type")
        if element_type == "checkbox":
            #如果id在爱好的id数组内则勾选
            if input.is_enabled() & (attr_id in ["c1", "c3"]) & (not input.is_selected()):
                input.click()
        elif element_type == "radio":
            #勾选喜欢现在的工作选项
            if (attr_id == "rlove") & input.is_enabled() & (not input.is_selected()):
                input.click() 

    这里用到了下面几个方法:

    • find_elements_by_tag_name根据标签名称获得元素列表

    • get_attribute获取某个属性

    • is_enabled方法是用于判断是否可用

    • is_selected方法是用于判断是否选中

    • is_displayed方法是用于判断是否显示

    运行输出结果如下:

    TIM图片20180204185534.png

    本文首发于学Python网:http://www.XuePython.wang

  • 相关阅读:
    《MySQL技术内幕》读书笔记
    CentOS裸机环境下安装php-7.3.1
    docker容器和本机互传文件
    一些数组操作函数记录
    window下强制删除文件
    根据一个镜像启动一个容器
    Nginx配置命令大全
    《Linux.Shell编程从入门到精通》读书笔记
    share drive 无效
    vi替换字符串
  • 原文地址:https://www.cnblogs.com/5bug/p/8503158.html
Copyright © 2020-2023  润新知