selenium对富文本框的处理

一般输入框有以下几种形式

第一种:短的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()" />&nbsp;&nbsp;
            <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

猜你喜欢

转载自www.cnblogs.com/cnhkzyy/p/9257877.html