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代码,就可以正常操作下拉框了。

  • 相关阅读:
    map的初级应用
    RB-Tree删除详解
    RB-Tree插入过程详解
    红黑树操作详解——很形象的过程
    一个数据结构可视化的神奇网址——形象理解
    关于B树B+树的详细解释——绝对精彩
    c++入门之函数指针和函数对象
    树的平衡之AVL树——错过文末你会后悔,信我
    二叉查找树的删除
    1 vmware 如何联网,以及行命令令初步
  • 原文地址:https://www.cnblogs.com/NancyRM/p/8250381.html
Copyright © 2011-2022 走看看