zoukankan      html  css  js  c++  java
  • Python+selenium(操作隐藏元素)

    测试过程中,偶尔会碰到一些页面的隐藏元素,如下,是小编举的一个简单的例子:

    test.html

    <html>
        <head></head>
        <body>
            <select style="display:none;">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="opel">Opel</option>
                <option value="audi">Audi</option>
            </select>
        </body>
    </html>

    按照一般正常的元素定位进行操作,如下:

    display.py

    from selenium import webdriver
    from selenium.webdriver.support.select import Select
    from time import sleep
    
    driver = webdriver.Firefox()
    driver.get(r"E:python_scriptBook	est.html")
    
    dr = driver.find_element_by_tag_name("select")
    Select(dr).select_by_value("saab")
    sleep(3)
    
    driver.quit()

    此时,运行代码结果是:

    selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with

    所以我们需要使用execute_script()方法,调用JavaScript代码修改display的值来实现

    display.py

    # ......
    js = 'document.querySelectorAll("select")[0].style.display="block";'
    driver.execute_script(js)
    
    dr = driver.find_element_by_tag_name("select")
    Select(dr).select_by_value("saab")
    # ......

    js代码分析:

    document.querySelectorAll("select")[0].style.display="block";

    document.querySelectorAll("select"):  选择所有的select类

    [0]:  指定这一组标签里的第几个

    style.display="block":  修改样式的display="block",表示可见

    执行完这句js代码,就可以正常操作下拉框了。

  • 相关阅读:
    vue封装一些常用组件loading、switch、progress
    个人推荐的两款vue导出EXCEL插件
    解决react项目中跨域和axios封装使用
    vue仿阿里云后台管理(附加阿里巴巴图标使用)
    简单的利用nginx部署前端项目
    Python3 SMTP发送邮件
    WINDOWS和UNIX换行符的理解
    Forward Proxy vs Reverse Proxy
    Authentication token is no longer valid
    SNMP Introduction
  • 原文地址:https://www.cnblogs.com/NancyRM/p/8250381.html
Copyright © 2011-2022 走看看