【selenium学习 -7】selenium操作下拉菜单

在使用之前需要导入Select模块

from selenium.webdriver.support.ui import Select

此次试验的HTML代码

<html>
    <select id ="select-test">
        <option value="wechat">微信</option>
        <option value="alipay">支付宝</option>
        <option value="crash">现金</option>
        <option value="card">刷卡</option>
    </select>
</html>

selenium定位下拉菜单的值有三种方式:

1.使用index定位
select_list.select_by_index(index)
2.使用value定位 select_list.select_by_value(value)
3.使用可见文本定位 select_list.select_by_visible_text(text)

测试代码:

from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select

if __name__ == '__main__':
    driver = webdriver.Chrome()
    driver.get(r"file:///E:/Project/Selenium/Select/select.html")
    driver.maximize_window()
    select_list = Select(driver.find_element_by_id("select-test"))
    # 获取下拉框的条目数量
    print(len(select_list.options))
    # 遍历下拉菜单的选项文本
    for i in select_list.options:
        print(i.text)
    # 1.使用index定位,定位到 微信
    select_list.select_by_index(0)
    time.sleep(5)
    # 2.使用value定位,定位到 支付宝
    select_list.select_by_value("alipay")
    time.sleep(5)
    # 3.使用可见文本定位,定位到 现金
    select_list.select_by_visible_text("现金")

总结:是select标签的可以如文章中的方式去操作,也有的下拉列表,并非标准的select标签,也可以直接粗暴的直接点击-点击-点击操作选中即可。

原文地址:https://www.cnblogs.com/ronyjay/p/12907318.html