測試過程中,偶爾會碰到一些頁面的隱藏元素,如下,是小編舉的一個簡單的例子:
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代碼,就可以正常操作下拉框了。