• selenium Select下拉框


    先来认识一下下拉框,以百度的“高级设置”为例

    介绍两种方法来处理下拉框:使用click事件,使用Select方法

    • 使用click事件

    上述下拉框的源代码如下:

    虽然我们可以在html源文件中看到select的各个选项,但是,如果我们没有定位到该下拉框的话,是定位不到里面的子选项的,

    所以使用click事件,需要一步一步的点击

    from selenium import webdriver
    driver=webdriver.Firefox()
    driver.get("https://www.baidu.com/gaoji/advanced.html")
    
    #定位搜索网页格式下拉框
    driver.find_element_by_name("ft").click()
    #通过xpath定位子选项
    option1=driver.find_element_by_xpath("//*[@name='ft']/option[1]")
    option2=driver.find_element_by_xpath("//*[@name='ft']/option[2]")
    option3=driver.find_element_by_xpath("//*[@name='ft']/option[3]")
    option4=driver.find_element_by_xpath("//*[@name='ft']/option[4]")
    #打印选项
    print(option1.text)
    print(option2.text)
    print(option3.text)
    print(option4.text)
    driver.quit()
    • 使用Select方法
    from selenium import webdriver
    #导入select模块
    from selenium.webdriver.support.select import Select
    
    driver=webdriver.Firefox()
    driver.get("https://www.baidu.com/gaoji/advanced.html")
    #d定位下拉框
    s=driver.find_element_by_name("ft")
    # #通过索引号,值从0开始,每一条option为一个索引
    option1=Select(s).select_by_index(0)
    option2=Select(s).select_by_index(2)
    # 通过value值,每个option都会有的属性
    option3=Select(s).select_by_value("pdf")
    option4=Select(s).select_by_value("doc")
    #通过文本,直接通过选项的文本来定位
    option5=Select(s).select_by_visible_text("微软 Powerpoint (.ppt)")
    option6=Select(s).select_by_visible_text("RTF 文件 (.rtf)")

    Select还提供了其他方法

    Select(s).all_selected_options  #返回所有选中的选项
    Select(s).options               #f返回所有选项
    Select(s).first_selected_option #返回该下拉框第一个选项
    Select(s).deselect_by_index()   #取消所有选项

    还有很多,不再一一列举,有兴趣可以自行研究

  • 相关阅读:
    微信开放平台(公众号第三方平台) -- 全网发布
    SQL 邮件配置篇
    让BI告诉你:圣诞老人去哪了?
    锁定和行版本控制
    数据库质疑修复总结(转)
    抢救损坏数据库中的数据
    将 PAGE_VERIFY 数据库选项设置为 CHECKSUM
    replicate复制函数
    @@IDENTITY与SCOPE_IDENTITY()
    RESTORE DATABASE的standby选项
  • 原文地址:https://www.cnblogs.com/wulisz/p/8082968.html
Copyright © 2020-2023  润新知