python使用selenium执行JS快速完成超长字符串的输入

使用selenium的 .send_keys 方法能够满足大多数情况的输入操作,但是在输入内容很多的情况下,使用该方法会消耗很多时间。

此时可以使用selenium执行js的  .innerHTMLf方法快速输入这些内容。

但是使用js的方法有一定缺陷性,它对常见  input标签类型的输入框无效,只对大多数富文本框生效。

非常简单的html界面

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>test</title>
    
</head>

<body bgcolor="burlywood">
    <div>
        <textarea id="kw1" cols="30" rows="10"></textarea>
        <hr>
        <textarea id="kw2" cols="30" rows="10"></textarea>
        <hr>
        <input id="kw3" value="">
    </div>
    
</body>

</html>

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("file:///E:/test.html")
search_str = "超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超" 
             "长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长" 
             "内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容" 
             "超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长" 
             "内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内" 
             "容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容" 
             "超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超" 
             "长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长" 
             "内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内" 
             "容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容" 
             "超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容超长内容"

# 使用innerHTML方式输入
js = f'document.getElementById("kw1").innerHTML="{search_str}";'
driver.execute_script(js)

# 使用send_keys方式输入
driver.find_element_by_id('kw2').send_keys(search_str)

# 在input框中使用innerHTML方式输入
js = f'document.getElementById("kw3").innerHTML="{search_str}";'
driver.execute_script(js)

原文地址:https://www.cnblogs.com/testlearn/p/12382747.html