操作策略:通过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>