操作策略:通過selenium提供的方法切換后進行操作
窗口切換:switch_to_window()
frame切換:switch_to_frame
窗口切換注意:窗口打開順序和窗口句柄列表索引的關系
頁面打開順序:1 2 3
窗口句柄索引:0 2 1
多窗口案例:
#coding=utf-8
from selenium import webdriver
import time,os
driver = webdriver.Chrome()
driver.get("https://www.hao123.com/")
driver.maximize_window()
#進入"鳳 凰 網",“優酷網”
driver.find_element_by_link_text("鳳 凰 網").click()
time.sleep(3)
driver.find_element_by_link_text("優 酷 網").click()
time.sleep(3)
#獲取所有窗口的窗口句柄
all_handle=driver.window_handles
print all_handle
#切換到“優酷網”
driver.switch_to_window(all_handle[1])
time.sleep(3)
#在“優酷網”繼續操作
driver.find_element_by_link_text("發現").click()
'''頁面打開順序和窗口句柄列表索引的關系
1 2 3
0 2 1
'''
內嵌frame案例:
Pyhon代碼
#coding=utf-8
from selenium import webdriver
import time
import os
driver = webdriver.Chrome()
file_path =os.path.abspath('frame.html')
driver.get(file_path)
#先找到到 ifrome1(id = f1)
driver.switch_to_frame("f1")
#再找到其下面的 ifrome2(id =f2)
driver.switch_to_frame("f2")
#下面就可以正常的操作元素了
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
time.sleep(3)
driver.quit()
內嵌frame HTML代碼
frame.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>frame</title>
</head>
<body>
<div class="row-fluid">
<div class="span10 well">
<h3>frame</h3>
<iframe id="f1" src="inner.html" width="800" height="600"></iframe>
</div>
</div>
</body>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>
inner.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>inner</title>
</head>
<body>
<div class="row-fluid">
<div class="span6 well">
<h3>inner</h3>
<iframe id="f2" src="http://www.baidu.com" width="700" height="400">
</iframe>
</div>
</div>
</body>
</html>
