Scenario:
Often encounter application frame / iframe form nested page in a Web application, WebDriver only the elements on a page identification and location, for a frame / iframe embedded form elements on the page can not be located directly. In this case it is necessary to switch to the current position of the body frame / iframe form by switch_to.frame () method embedded page.
frame.html
1 <html> 2 <head> 3 <link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.mincss" rel="stylesheet" /> 4 <script type="text/javascript">$(document).ready(function(){});</script> 5 </head> 6 <body> 7 <div class="row-fluid"> 8 <div class="span10 well"> 9 <h3>frame</h3> 10 <iframe id="if" name="nf" src="http://www.baidu.com" width="1600" height="800"></iframe> 11 </div> 12 </div> 13 </body> 14 <script src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script> 15 </html>
In the above html code I embedded in a page via an iframe Baidu form, open a browser as shown:
This time Baidu input box located directly on the page will error: Element not found. So you can use switch_to.frame () to find the frame.html
1 #导包 2 from selenium import webdriver 3 from time import sleep 4 #定义浏览器句柄 5 driver=webdriver.Chrome() 6 #打开本地frame.html 7 url="file:///C:/Users/Charseki/Desktop/Web%E8%87%AA%E5%8A%A8%E5%8C%96/iframe%E5%A4%9A%E8%A1%A8%E5%8D%95%E5%88%87%E6%8D%A2/frame.html" 8 driver.get(url) 9 #窗口最大化 10 driver.maximize_window() 11 #直接去拿百度输入框元素 12 #driver.find_element_by_xpath('//input[@id="kw"]') 13 #发现报错,因为元素在iframe表单里面 14 #正确的方法:进入到iframe表单,再去获取百度输入框元素 15 driver.switch_to.frame(driver.find_element_by_xpath('//iframe[contains(@src,"www.baidu.com")]')) 16 driver.find_element_by_xpath('//input[@id="kw"]').send_keys("可以操作元素了") 17 #点击“百度一下”按钮 18 driver.find_element_by_xpath('//input[@id="su"]').click() 19 sleep(3) 20 driver.quit()
switch_to.frame()默认可以直接取表单的id或name属性。如果iframe没有可以用的id和name属性,则可以通过下面的方式进行定位。
1 #先通过xpath定位到iframe 2 xf=driver.find_element_by_xpath('//*[@class="if"]') 3 #再将定位对象传给switch_to.frame()方法 4 driver.switch_to.frame(xf) 5 ...... 6 driver.switch_to.parent_frame()
如果完成了在当前表单上的操作,则可以通过switch_to.parent_frame()方法跳出当前一级表单。该方法默认对应于离它最近的switch_to.frame()方法。除此之外,在进入多级表单的情况下,还可以通过switch_to.default_content()跳回最外层的页面。
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Talk is cheap,show me the code.