4.9 selenium 多表单切换

bootstrap框架

frame.html实现的效果

在web应用中经常会遇到 frame/iframe 表单内嵌页面上的元素无法直接定位。这时就需要通过 switch_to.frame() 方法将当前定位的主体切换为 frame/iframe 表单的内嵌页面内

<!--frame.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://github.com/bootcdn/BootCDN/blob/1.0.1/ajax/libs/bootstrap/3.3.0/css/bootstrap-theme.min.css">

</head>
<body>
<!--selenium自动化测试 4.9 多表单切换-->
    <div class="row-fluid">
        <div class="span10 well">
            <h3>frame</h3>
            <iframe src="http://baidu.com" frameborder="0" id="nf" name="nf" width="800" height="300"></iframe>
        </div>
    </div>
</body>
<script src="https://github.com/bootcdn/BootCDN/blob/1.0.1/ajax/libs/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</html>

通过 switch_to.frame() 先找到 frame.html 中的 <iframe> 标签,然后再定位百度输入框。

#frame.py
from selenium import webdriver
import os,time

#selenium自动化测试 4.9 多表单切换
class Frame():
    def setup_method(self):
        self.driver = webdriver.Chrome()
        self.file_path = 'file:///' + os.path.abspath('frame.html')
        self.driver.get(self.file_path)

    def teardown_method(self):
        self.driver.quit()

    def frame(self):
        #切换到iframe(id = "nf")
        self.driver.switch_to.frame("nf")
        #下面就可以正常的操作元素了
        self.driver.find_element_by_id("kw").send_keys("selenium")
        self.driver.find_element_by_id("su").click()
        time.sleep(3)


if __name__ == '__main__':
    frame = Frame()
    frame.setup_method()
    frame.frame()
    frame.teardown_method()


warning :未经授权,不得转载
有问题的小伙伴请在下方留言,喜欢就点个赞吧;关注我,带你一起写bug
CSDN:带只拖鞋去流浪
知乎:叄贰壹

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容