Selenium-Webdriver系列Python版教程(5)————如何定位 frame

在 web ui 自動化測試中,frame 一直是使人頭痛的問題,就像上班必須擠公車坐地鐵通常,html

frame 的問題老是使人氣悶糾結爲之黯然神傷。web

之前在使用 Selenium1 的時候,frame 也是頗爲棘手的一個問題。不但要照本宣科的進行框架

一系列的設置,並且在進行實際代碼編寫的過程當中會遇到各類奇奇怪怪的問題。 frame 就像工具

中國男足的後防線,問題多多難以解決。測試

selenium webdriver 處理 frame 比較簡單,這點比某些測試工具要先進一些,使人身心愉ui

悅。spa

如下面的 html 代碼爲例,咱們看一下如何定位 frame 上的元素。orm

frame.htmlhtm

<html>對象

<head>
<title>frame</title>

</head>

<body>

<div class="row-fluid">
<div class="span10 well">
<h3>frame</h3>
<iframe id="f1" src=" part1 .html" width="800",
height="600"></iframe>
</div>
</div>
</body>

</html>


part1.htm

<html>

<head>
<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="500"></iframe>
</div>
</div>
</body>

</html>


switch_to 方法會 new1個 TargetLocator 對象,使用該對象的 frame 方法能夠將當前識別

的」主體」移動到須要定位的 frame 上去。

from selenium import webdriver

import os,time

objDriver = webdriver.Chrome ()

#相對路徑(與Python文件在同一個目錄下)

frame_file = 'file://"+ os.getcwd()  + '/frame.html'))

objDriver.get(file_path)

objDriver.implicitly_wait(30)

#先找到到ifrome1(id = f1)

objDriver.switch_to_frame("f1")

#再找到其下面的ifrome2(id =f2)

objDriver.switch_to_frame("f2")

#操做f2中的控件

objDriver.find_element_by_id("kw").send_keys("selenium")

time.sleep(5)

objDriver.quit()

webdriver 的 frame 處理方式讓人感受那個不痛愈來愈輕鬆,這點進步值得確定。

備註:

browser.implicitly_wait()的用法應該比time.sleep() 更智能,後者只能選擇一個固定的時間的等待,前者能夠在一個時間範圍內智能的等待。

 

driver.switch_to_window()的用法與switch_to_frame 相同,只是switch_to_window()不是對嵌套的框架定位,而是窗口的定位。

相關文章
相關標籤/搜索