zoukankan      html  css  js  c++  java
  • Python+Selenium-select

    场景

    在处理下拉框(select)的时候selenium给我们提供了一系列的便捷方法,我们只需要使用selenium.webdriver.support.select.Select类来稍微封装一下就好了。

    下面是我们经常会用到的一些方法

    • options: 返回下拉框里所有的选项
    • all_selected_options: 返回所有选中的选项
    • select_by_value(value): 通过option的value值来选择
    • select_by_index(index) 通过option的顺序来选择
    • select_by_visible_text(text): 通过option的text来选择

    代码

    s7.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form enctype="multipart/form-data">
            <div>
     
                <textarea name="meno" >123456</textarea>
     
                <select name="city"  >
                    <option value="beijing">北京</option>
                    <option value="shanghai">上海</option>
                    <option value="nanjing" selected="selected">南京</option>
                    <option value="chengdu">成都</option>
                </select>
     
            <input type="submit" value="提交" />
            <input type="reset" value="重置" />
            </div>
        </form>
    </body>
    </html>

      select--tag.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    #!/usr/bin/env python
    # -*- codinfg:utf-8 -*-
    '''
    @author: Jeff LEE
    @file: select--tag.pay
    @time: 2020-02-28 10:44
    '''
    from selenium import webdriver
    from selenium.webdriver.support.select import Select
    from time import sleep
    import os
     
    if 'HTTP_PROXY'in os.environ:
        del os.environ['HTTP_PROXY']
     
    dr = webdriver.Firefox()
    file_path ='file://'+ os.path.abspath('s7.html')
    print (file_path)
    dr.get(file_path)
     
    city_selector = Select(dr.find_element_by_tag_name('select'))
     
    # 返回所有的options
    print(city_selector.options)
    sleep(1)
     
    # 返回所有选中的options
    print(city_selector.all_selected_options)
    sleep(1)
     
    # 通过option的value值来选择上海
    city_selector.select_by_value('shanghai')
    sleep(2)
     
    # 通过index来选择,比如选择第4项
    city_selector.select_by_index(3)
    sleep(1)
     
    # 通过option的text来选择
    city_selector.select_by_visible_text('北京')
     
    dr.quit()
  • 相关阅读:
    929. 独特的电子邮件地址
    [工具.tcp]测试TCP通讯的网络延迟
    [技巧.Dotnet]轻松实现“强制.net程序以管理员身份运行”。
    [问题记录.VisualStudio]VS2013无法新增和打开项目
    [问题记录.VisualStudio]TFS项目映射问题解决
    [问题记录.dotnet]取网卡信息报错"找不到"-WMI
    模型驱动的数学原理
    剑指OFFER 旋转数组的最小数字
    剑指OFFER 用两个栈实现队列
    剑指OFFER 按之字形顺序打印二叉树
  • 原文地址:https://www.cnblogs.com/chenlimei/p/12781596.html
Copyright © 2011-2022 走看看