一般輸入框有以下幾種形式
第一種:短的input框
如百度首頁的輸入框,<input type="text" class="s_ipt" name="wd" id="kw" maxlength="100" autocomplete="off">,百度輸入框的值不在text中,是在value屬性中
又驗證了一下,自己寫的簡單的登錄界面的輸入框,發現確實也是這樣的,html代碼為
<html> <head> <meta charset="utf-8"> <title>html表單作業-2</title> <script type="text/javascript"> function myFunc(){ var username = document.getElementById("username").value; confirm("用戶名為:" + username); } </script> </head> <body> <form> 用戶名:<input type="text" id="username" name="username" /> <br /> 密碼:<input type="password" id="passwd" name="passwd" /> <br /> <input type="button" value="登錄" onclick="myFunc()" /> <input type="reset" value="重置" /> </form> </body> </html>
解決辦法:driver.find_element_by_id("kw").send_keys("需要輸入的內容")
第二種:div式的editor框
比如QQ郵箱寫郵件,因此這種也采用的是send_keys的方法,只不過這個值不在value屬性中,而是在text中
第三種:textarea
以博客園的博文評論為例,發現文本值也是保存在value中的
和百度輸入框不同,雖然百度輸入框中的文本值也是存在value中,但它可以通過send_keys的方法來發送值,但這種必須要用到js
from selenium import webdriver import time option = webdriver.ChromeOptions() option.add_argument("--user-data-dir=C:\\Users\\Beck\\AppData\\Local\\Google\\Chrome\\User Data") driver = webdriver.Chrome(options=option) driver.get("https://www.cnblogs.com/cnhkzyy/p/9253272.html") time.sleep(3) textarea_element = driver.find_element_by_id("tbCommentBody") driver.execute_script("arguments[0].focus();", textarea_element) time.sleep(2) driver.execute_script("arguments[0].value='test comment'", textarea_element) time.sleep(2) driver.find_element_by_id("btn_comment_submit").click() time.sleep(3) driver.quit()
可以看到評論的確提交成功了
第四種:iframe中的editor
示例的網站是:http://ueditor.baidu.com/website/examples/completeDemo.html
我們可以看到,內容為空時,直接定位到了body,再仔細看看,原來還有個iframe
有了內容之后,<body>標簽下會自動加一些<p>標簽,文本內容就在<p>標簽的text中
所以,對於這種情況,先切換到iframe,再向<body>標簽直接send_keys,簡單粗暴
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("http://ueditor.baidu.com/website/examples/completeDemo.html") time.sleep(2) #通過id切換到iframe driver.switch_to.frame("ueditor_0") content = """This is a test content! This is a test content! This is a test content! """ driver.find_element_by_tag_name("body").send_keys(content) print(driver.find_element_by_tag_name("body").text)
運行結果:
python控制台輸出:
This is a test content! This is a test content! This is a test content!
參考文章
https://www.cnblogs.com/xiaobaichuangtianxia/p/5889999.html