随笔 - 62  文章 - 0 评论 - 6 阅读 - 25万
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

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

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

 

posted on   NancyRM  阅读(5364)  评论(0编辑  收藏  举报
(评论功能已被禁用)
点击右上角即可分享
微信分享提示