在web应用中经常会遇到frame/iframe表单嵌套,这时就需要switch_to.frame()跳转到表单的内嵌网页中定位元素
frame.html
<html>
<head>
<link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css"
rel="stylesheet" />
<script type="text/javascript">$(document).ready(function(){
});
</script>
</head>
<body>
<div class="row-fluid">
<div class="span10 well">
<h3>frame</h3>
<iframe id="if" name="nf" src="http://www.baidu.com" width="800"
height="300">
</iframe>
</div>
</div>
</body>
<script
src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script>
</html>
表单跳转
from selenium import webdriver
import time
driver=webdriver.Chrome()
file_path='d:/frame.html'
driver.get(file_path)
#切换到id=if
driver.switch_to.frame('if')
driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()
time.sleep(3)
driver.quit()
完成在表单中操作后,可以通过switch_to.parent_content()方法跳出当前一级表单,如果进入的是多级表单,可使用switch_to.default_content()跳到最外层页面