python下彻底解决浏览器多标签打开与切换问题

时间:2021-01-26 08:17:01

#coding:utf-8
#Right_key_click and Tad switch
#by dengpeiyou date:2018-7-7
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
brow=webdriver.Firefox()

# First Tab
brow.get("https://www.baidu.com")
brow.maximize_window()
tab_1 = brow.current_window_handle
print('第一个标签页的标题:'+brow.title)
time.sleep(3)

# Second Tab
brow.find_element_by_tag_name("body").send_keys(Keys.CONTROL + "t")
brow.get("http://mail.126.com")
tab_2 = brow.current_window_handle
print('第二个标签页的标题:'+brow.title)
time.sleep(3)

# Back First Tab
brow.find_element_by_tag_name("body").send_keys(Keys.CONTROL + Keys.PAGE_UP)
brow.switch_to_window(tab_1)
print('当前标签页的标题:'+brow.title)
time.sleep(3)

#Right_key_click
e1=brow.find_element_by_tag_name('area')
ActionChains(brow).context_click(e1).perform()
e1.send_keys('t')
time.sleep(3)
brow.find_element_by_tag_name("body").send_keys(Keys.CONTROL + Keys.PAGE_DOWN)
tab_3 = brow.current_window_handle
brow.switch_to_window(tab_1)
print('当前标签页的标题:'+brow.title)
time.sleep(5)

brow.quit()