之前章节,分别对窗口切换(handle)、frame切换、弹窗(alert)切换做了详细的解释,但是我们在写代码的时候发现,这些方法都被编辑器划伤了一条横线,但是方法还是可以正常使用,只是目前的pycharm不推荐你继续这样使用了(有新的方法可以替代它),那如果我们不使用这些方法的话,我们该怎么去完成切换窗口、frame这些操作呢?所以我们来学习一下替代这几个方法的switch_to包。
一、switch_to包的方法详解
在switch_to的基础上,有这么几个方法,鉴于基本上都是之前曾经讲过的,这次把等价的方法也列出来,供大家参考
driver.switch_to.parent_frame()
这是switch_to中独有的方法,可以切换到上一层的frame,对于层层嵌套的frame很有用
案例展示:
163邮箱登录的例子来用新的switch_to方法写一下,并通过观察,我们发现进入这个页面后焦点直接就定位到输入框里了,所以我们可以通过active_element()来定位。
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
# 进入163邮箱首页
driver.get("http://mail.163.com/")
sleep(2)
# 切换到包含登录框的frame下
driver.switch_to.frame(1)
# 通过定位输当前焦点元素,并再次输入数据
ele_box = driver.switch_to.active_element
ele_box.send_keys("123")
switch_to源码
class SwitchTo:
def __init__(self, driver):
self._driver = driver
@property
def active_element(self):
"""
Returns the element with focus, or BODY if nothing has focus.
:Usage:
element = driver.switch_to.active_element
"""
if self._driver.w3c:
return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)
else:
return self._driver.execute(Command.GET_ACTIVE_ELEMENT)['value']
@property
def alert(self):
"""
Switches focus to an alert on the page.
:Usage:
alert = driver.switch_to.alert
"""
return Alert(self._driver)
def default_content(self):
"""
Switch focus to the default frame.
:Usage:
driver.switch_to.default_content()
"""
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': None})
def frame(self, frame_reference):
"""
Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
driver.switch_to.frame('frame_name')
driver.switch_to.frame(1)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
"""
if isinstance(frame_reference, basestring) and self._driver.w3c:
try:
frame_reference = self._driver.find_element(By.ID, frame_reference)
except NoSuchElementException:
try:
frame_reference = self._driver.find_element(By.NAME, frame_reference)
except NoSuchElementException:
raise NoSuchFrameException(frame_reference)
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
def parent_frame(self):
"""
Switches focus to the parent context. If the current context is the top
level browsing context, the context remains unchanged.
:Usage:
driver.switch_to.parent_frame()
"""
self._driver.execute(Command.SWITCH_TO_PARENT_FRAME)
def window(self, window_name):
"""
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
driver.switch_to.window('main')
"""
data = {'name': window_name}
if self._driver.w3c:
data = {'handle': window_name}
self._driver.execute(Command.SWITCH_TO_WINDOW, data)