1. 程式人生 > >Selenium3+webdriver學習筆記6(多視窗切換處理)

Selenium3+webdriver學習筆記6(多視窗切換處理)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

import time,os

# about:addons 火狐瀏覽器安裝元件,訪問的地址

# <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
# <input type="submit" value="百度一下" id="su" class="btn self-btn bg s_btn">
#id
keys="工作"
delay=3
url="http://sz.ganji.com/"
driver=webdriver.Firefox()

driver.get(url)

#等待delay秒
driver.implicitly_wait(delay)

#當前視窗控制代碼
cur_handle=driver.current_window_handle

#獲取所有控制代碼
driver.find_element_by_link_text(keys).click()
all_handle=driver.window_handles

# #切換控制代碼方法1
for i in all_handle:
if i!=cur_handle:
driver.switch_to.window(i)
#
# #切換控制代碼方法2
driver.switch_to.window(all_handle[1])
print(driver.title)

# 切回到首頁視窗
driver.close()
driver.switch_to.window(cur_handle)
print(driver.title)

#等待delay秒
time.sleep(delay)

# # 退出當前視窗
driver.close()

# 退出所有視窗
driver.quit()