Python+selenium(操作非表示要素)

5212 ワード

テスト中、たまにページの非表示要素に遭遇します.以下のように、簡単な例です.
test.html
<html>
    <head>head>
    <body>
        <select style="display:none;">
            <option value="volvo">Volvooption>
            <option value="saab">Saaboption>
            <option value="opel">Opeloption>
            <option value="audi">Audioption>
        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コードを実行すると、ドロップダウンボックスを正常に操作できます.
 
転載先:https://www.cnblogs.com/NancyRM/p/8250381.html