介绍
###### 测试的系统:白月黑羽网站的测试系统(白月SMS系统)
###### 测试内容:点击【学习教程】链接跳转到白月黑羽网站,获取此网站上的标题,然后回到原来的系统。
###### 所涉及的知识点:frame切换/窗口切换
这个iframe元素非常的特殊,在html语法中,frame元素或者iframe元素的内容**会包含一个被嵌入的零一份html文档**。
在我们使用selenium打开一个网页是,我们的操作范围缺省是当前的html,并不包含被嵌入的html文档里面的内容。
如果我们要操作被嵌入的html文档中的元素,就必须切换操作范围到被嵌入的文档中。
* **切换到Frame(3种方式)**
```python
# 方式1:通过索引切换(第1个iframe,从0开始)
driver.switch_to.frame(0)
# 方式2:通过 name 或 id 属性切换
driver.switch_to.frame("frame-name") # name="frame-name"
driver.switch_to.frame("frame-id") # id="frame-id"
# 方式3:通过 WebElement 对象切换(最灵活,推荐)
iframe = driver.find_element(By.CSS_SELECTOR, "iframe.class-name")
driver.switch_to.frame(iframe)
```
* **切回主文档/父级Frame**
```python
# 切回父级 Frame(如果有多层嵌套,只向上退一层)
driver.switch_to.parent_frame()
# 切回最外层的主文档(彻底退出所有 iframe)
driver.switch_to.default_content()
```
自动化测试程序
python
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Redirect:
def __init__(self):
self.driver = webdriver.Chrome()
def Login(self,username,password):
self.driver.get('http://127.0.0.1/mgr/sign.html')
usernameElement = self.driver.find_element(By.ID, 'username')
usernameElement.send_keys(username)
sleep(2)
passwordElement = self.driver.find_element(By.ID, 'password')
passwordElement.send_keys(password)
sleep(2)
# 点击登录
submitElement = self.driver.find_element(By.XPATH, "//div[@class='col-xs-12']/button")
submitElement.click()
sleep(2)
print('登录成功~')
def RedirectByhy(self):
#mainWindow变量保存当前窗口的句柄
mainWindow = self.driver.current_window_handle
#定位跳转的新窗口链接
iframe = self.driver.find_element(By.XPATH,'//footer/div/a')
href = iframe.get_attribute('href')
iframe.click()
# 等待新窗口出现(窗口数量增加)
WebDriverWait(self.driver, 10).until(EC.number_of_windows_to_be(2))
#切换到新窗口
for handle in self.driver.window_handles:
if handle != mainWindow:
self.driver.switch_to.window(handle)
break
self.driver.get(f'{href}')
sleep(2)
titleElements = self.driver.find_elements(By.XPATH,'//div[@id="nav-topics"]/a')
for title in titleElements:
print(title.text)
print('【本次测试结束!!!!】')
if __name__ == '__main__':
Re = Redirect()
Re.Login('byhy','88888888')
Re.RedirectByhy()