Python 如何切换到Selenium中的活动选项卡?

Python 如何切换到Selenium中的活动选项卡?,python,selenium,google-chrome-extension,Python,Selenium,Google Chrome Extension,我们开发了一个Chrome扩展,我想用Selenium测试我们的扩展。我创建了一个测试,但问题是我们的扩展在安装时会打开一个新选项卡,我想我从另一个选项卡中得到了一个异常。是否可以切换到我正在测试的活动选项卡?或者另一种选择是先禁用扩展,然后登录我们的网站,然后才启用扩展。可能吗?这是我的密码: def login_to_webapp(self): self.driver.get(url='http://example.com/logout') self.driver.maxim

我们开发了一个Chrome扩展,我想用Selenium测试我们的扩展。我创建了一个测试,但问题是我们的扩展在安装时会打开一个新选项卡,我想我从另一个选项卡中得到了一个异常。是否可以切换到我正在测试的活动选项卡?或者另一种选择是先禁用扩展,然后登录我们的网站,然后才启用扩展。可能吗?这是我的密码:

def login_to_webapp(self):
    self.driver.get(url='http://example.com/logout')
    self.driver.maximize_window()
    self.assertEqual(first="Web Editor", second=self.driver.title)
    action = webdriver.ActionChains(driver=self.driver)
    action.move_to_element(to_element=self.driver.find_element_by_xpath(xpath="//div[@id='header_floater']/div[@class='header_menu']/button[@class='btn_header signature_menu'][text()='My signature']"))
    action.perform()
    self.driver.find_element_by_xpath(xpath="//ul[@id='signature_menu_downlist'][@class='menu_downlist']/li[text()='Log In']").click()
    self.driver.find_element_by_xpath(xpath="//form[@id='atho-form']/div[@class='input']/input[@name='useremail']").send_keys("[email]")
    self.driver.find_element_by_xpath(xpath="//form[@id='atho-form']/div[@class='input']/input[@name='password']").send_keys("[password]")
    self.driver.find_element_by_xpath(xpath="//form[@id='atho-form']/button[@type='submit'][@class='atho-button signin_button'][text()='Sign in']").click()
测试失败,出现
ElementNotVisibleException:Message:element不可见
,因为在新选项卡(由扩展打开)中,“登录”不可见(我认为新选项卡仅在命令
self.driver.get(url=)后打开)http://example.com/logout)

更新:我发现异常与额外选项卡无关,它来自我们的网站。但根据@aberna的回答,我用这个代码关闭了额外的标签:

def close_last_tab(self):
    if (len(self.driver.window_handles) == 2):
        self.driver.switch_to.window(window_name=self.driver.window_handles[-1])
        self.driver.close()
        self.driver.switch_to.window(window_name=self.driver.window_handles[0])

关闭额外选项卡后,我可以在视频中看到我的选项卡。

一些可能的方法:

1-使用发送键(CONTROL+TAB)在选项卡之间切换

2-使用操作图标(CONTROL+选项卡)在选项卡之间切换

3-另一种方法可以使用Selenium方法检查当前窗口并移动到另一个窗口:

你可以用

driver.window_handles
要查找窗口句柄列表,请尝试使用以下方法进行切换

- driver.switch_to.active_element      
- driver.switch_to.default_content
- driver.switch_to.window
例如,要切换到上次打开的选项卡,可以执行以下操作:

driver.switch_to.window(driver.window_handles[-1])

这实际上在3.x中对我有效:

driver.switch_to.window(driver.window_handles[1])
窗口句柄被追加,因此这将选择列表中的第二个选项卡

要继续使用第一个选项卡,请执行以下操作:

driver.switch_to.window(driver.window_handles[0])

被接受的答案对我不起作用。
要打开一个新选项卡并让selenium切换到它,我使用了:

driver.execute_script('''window.open("https://some.site/", "_blank");''')
sleep(1) # you can also try without it, just playing safe
driver.switch_to.window(driver.window_handles[-1]) # last opened tab handle  
# driver.switch_to_window(driver.window_handles[-1]) # for older versions
如果需要切换回主选项卡,请使用:

driver.switch_to.window(driver.window_handles[0])

总结:

窗口句柄
包含打开的
选项卡的
句柄列表
,将其用作
切换到.window()
中的参数以在选项卡之间切换。

按ctrl+t或选择
窗口句柄[0]
假定启动时只有一个选项卡打开

如果您打开了多个选项卡,则可能会变得不可靠

我就是这么做的:

old_tabs=self.driver.window_handles
#Perform action that opens new window here
new_tabs=self.driver.window_handles
for tab in new_tabs:
     if tab in old tabs:
          pass
     else:
          new_tab=tab
driver.switch_to.window(new_tab)
这将在切换到新选项卡之前确定新选项卡,并将活动窗口设置为所需的新选项卡


仅仅告诉浏览器发送ctrl+tab不起作用,因为它没有告诉webdriver实际切换到新选项卡。

找到了使用ahk库的方法。对于我们这些需要解决这个问题的非程序员来说非常容易。使用Python 3.7.3

安装ahk时,请使用。pip安装ahk
这是完整的脚本

注意:删除下面两行中微小URL的空格。堆栈溢出不允许此处存在微小链接

import ahk
import win32clipboard
import traceback
import appJar
import requests
import sys
import urllib
import selenium
import getpass
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import socket
import time 
import urllib.request
from ahk import AHK, Hotkey, ActionChain # You want to play with AHK. 
from appJar import gui

try:                                                                                                                                                                         
    ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")    

except:                                                                                                                                                                         
    ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")    

finally:                                                                                                                                                                         
    pass 

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--start-maximized')
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation']);
chromeDriver = webdriver.Chrome('C:\\new_software\\chromedriver.exe', chrome_options = chrome_options)

def  ahk_disabledevmodescript():
    try:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
    except:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
    finally:                                                                                                                                                                         
        pass   
    ahk_disabledevmodescriptt= [
    str('WinActivate,ahk_exe chrome.exe'),
    str('Send {esc}'),
    ]
    #Run-Script
    for snipet in  ahk_disabledevmodescriptt:
        ahk.run_script(snipet, blocking=True )
    return 

def launchtabsagain():

    chromeDriver.execute_script("window.open('https://developers.google.com/edu/python/introduction', 'tab2');")
    chromeDriver.execute_script("window.open('https://www.facebook.com/', 'tab3');")
    chromeDriver.execute_script("window.open('https://developer.mozilla.org/en-US/docs/Web/API/Window/open', 'tab4');")
    chromeDriver.execute_script("window.open('https://www.easyespanol.org/', 'tab5');")
    chromeDriver.execute_script("window.open('https://www.google.com/search?source=hp&ei=EPO2Xf3EMLPc9AO07b2gAw&q=programming+is+not+difficult&oq=programming+is+not+difficult&gs_l=psy-ab.3..0i22i30.3497.22282..22555...9.0..0.219.3981.21j16j1......0....1..gws-wiz.....6..0i362i308i154i357j0j0i131j0i10j33i22i29i30..10001%3A0%2C154.h1w5MmbFx7c&ved=0ahUKEwj9jIyzjb_lAhUzLn0KHbR2DzQQ4dUDCAg&uact=5', 'tab6');")
    chromeDriver.execute_script("window.open('https://www.google.com/search?source=hp&ei=NvO2XdCrIMHg9APduYzQDA&q=dinner+recipes&oq=&gs_l=psy-ab.1.0.0i362i308i154i357l6.0.0..3736...0.0..0.179.179.0j1......0......gws-wiz.....6....10001%3A0%2C154.gsoCDxw8cyU', 'tab7');")

    return  
chromeDriver.get('https://ebc.cybersource.com/ebc2/')
compoanionWindow = ahk.active_window

launchtabs = launchtabsagain()
disabledevexetmessage = ahk_disabledevmodescript()



def copyUrl(): 
    try:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
    except:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
    finally:                                                                                                             

        pass 
    snipet = str('WinActivate,ahk_exe chrome.exe')
    ahk.run_script(snipet, blocking=True )  
    compoanionWindow.activate() 
    ahk_TinyChromeCopyURLScript=[

        str('WinActivate,ahk_exe chrome.exe'),
        str('send ^l'),
        str('sleep 10'),
        str('send ^c'),
        str('BlockInput, MouseMoveoff'),
        str('clipwait'),
    ] 

    #Run-AHK Script
    if ahk:
        for snipet in  ahk_TinyChromeCopyURLScript:
            ahk.run_script(snipet, blocking=True )  
    win32clipboard.OpenClipboard()
    urlToShorten = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()   


    return(urlToShorten)


def tiny_url(url):
    try:

        apiurl = "https: // tinyurl. com / api - create. php? url= " #remove spaces here
        tinyp = requests.Session()
        tinyp.proxies = {"https" : "https://USER:PASSWORD." + "@userproxy.visa.com:443", "http" : "http://USER:PASSWORD." + "@userproxy.visa.com:8080"}
        tinyUrl = tinyp.get(apiurl+url).text
        returnedresponse = tinyp.get(apiurl+url)
        if returnedresponse.status_code == 200: 
            print('Success! response code =' + str(returnedresponse))
        else:
            print('Code returned = ' + str(returnedresponse))
            print('From IP Address =' +IPadd)


    except:
        apiurl = "https: // tinyurl. com / api - create. php? url= " #remove spaces here
        tinyp = requests.Session()
        tinyUrl = tinyp.get(apiurl+url).text
        returnedresponse = tinyp.get(apiurl+url)
        if returnedresponse.status_code == 200: 
            print('Success! response code =' + str(returnedresponse))
            print('From IP Address =' +IPadd)
        else:
            print('Code returned = ' + str(returnedresponse))

    return tinyUrl

def tinyUrlButton():

    longUrl = copyUrl()
    try:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
    except:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
    finally:                                                                                                                                                                         
        pass
    try:
        shortUrl = tiny_url(longUrl)
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(shortUrl)
        win32clipboard.CloseClipboard()
        if ahk:
            try:
                if str(shortUrl) == 'Error':
                    ahk.run_script("Msgbox,262144 ,Done.,"+ shortUrl + "`rPlease make sure there is a link to copy and that the page is fully loaded., 5.5" )
                else:
                    ahk.run_script("Msgbox,262144 ,Done.,"+ shortUrl + " is in your clipboard., 1.5" )
                # ahk.run_script("WinActivate, tinyUrl" )
            except:
                traceback.print_exc()
                print('error during ahk script')

                pass

    except:
        print('Error getting tinyURl')
        traceback.print_exc()

def closeChromeTabs(): 
        try: 
            try:                                                                                                                                                                          
                ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                          
            except:                                                                                                                                                                          
                ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                  
            finally:                                                                                                                                                                          
                    pass   
            compoanionWindow.activate()  
            ahk_CloseChromeOtherTabsScript = [ 

                str('WinActivate,ahk_exe chrome.exe'), 
                str('Mouseclick, Right, 30, 25,,1'), 
                str('Send {UP 3} {enter}'), 
                str('BlockInput, MouseMoveOff'), 
                ] 
                #Run-Script 
            if ahk: 
                for snipet in  ahk_CloseChromeOtherTabsScript: 
                        ahk.run_script(snipet, blocking=True ) 
            return(True) 
        except: 
            traceback.print_exc() 
            print("Failed to run closeTabs function.") 
            ahk.run_script('Msgbox,262144,,Failed to run closeTabs function.,2') 
            return(False)         



        # create a GUI and testing this library.

window = gui("tinyUrl and close Tabs test ", "200x160")
window.setFont(9)
window.setBg("blue")
window.removeToolbar(hide=True)
window.addLabel("description", "Testing AHK Library.")
window.addLabel("title", "tinyURL")
window.setLabelBg("title", "blue")
window.setLabelFg("title", "white")
window.addButtons(["T"], tinyUrlButton)
window.addLabel("title1", "Close tabs")
window.setLabelBg("title1", "blue")
window.setLabelFg("title1", "white")
window.addButtons(["C"], closeChromeTabs)
window.addLabel("title2", "Launch tabs")
window.setLabelBg("title2", "blue")
window.setLabelFg("title2", "white")
window.addButtons(["L"], launchtabsagain)
window.go()

if window.exitFullscreen():
    chromeDriver.quit()


def closeTabs():
    try:
        try:                                                                                                                                                                         
            ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
        except:                                                                                                                                                                         
            ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
        finally:                                                                                                                                                                         
                pass   

        compoanionWindow.activate()     
        ahk_CloseChromeOtherTabsScript = [

            str('WinActivate,ahk_exe chrome.exe'),
            str('Mouseclick, Right, 30, 25,,1'),
            str('Send {UP 3} {enter}'),
            str('BlockInput, MouseMoveOff'),
            ]
            #Run-Script
        if ahk:
            for snipet in  ahk_CloseChromeOtherTabsScript:
                    ahk.run_script(snipet, blocking=True )
        return(True)
    except:
        traceback.print_exc()
        print("Failed to run closeTabs function.")
        ahk.run_script('Msgbox,262144,Failed,Failed to run closeTabs function.,2')
        return(False)
用户“aberna”的提示对我的作用如下:

首先,我得到了选项卡列表:

  tab_list = driver.window_handles
然后我选择设置选项卡:

   driver.switch_to.window(test[1])
返回上一选项卡:

    driver.switch_to.window(test[0])

如果只想关闭活动选项卡并需要保持浏览器窗口打开,可以使用switch_to.window方法,该方法的输入参数为window handle-id。以下示例显示了如何实现此自动化:

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get('https://www.google.com')

driver.execute_script("window.open('');")
time.sleep(5)

driver.switch_to.window(driver.window_handles[1])
driver.get("https://facebook.com")
time.sleep(5)

driver.close()
time.sleep(5)

driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.yahoo.com")
time.sleep(5)

#driver.close()

它不工作,我想它不会切换选项卡,因为在视频[]中,我看到活动选项卡是相同的。@Uri不太容易通过视频分析行为。我用另一个可能的答案更新了答案approach@Uri解决您问题的方法是什么?我认为如果第二个选项卡有文本输入,并且selenium在其中输入文本,则此方法将不起作用-至少在我的情况下是这样。我在使用新选项卡时遇到问题,此方法节省了时间
driver。切换到\u窗口(driver.window\u句柄[1])
它看起来很粗糙,但如果您知道您的测试站点应该在一个新选项卡中打开一个链接,而不是其他选项卡,则效果很好。非常适合快速和肮脏。@sdkks对不起,我不明白你的意思。抱歉,如果我的评论愚蠢或冒犯他人,那不是故意的。我使用了这个代码,它工作得很好。你能详细解释一下为什么它看起来很粗糙吗?我所说的“你”并不是指“你,用户sdkks”,而是除了“测试站点应该在一个新选项卡中打开链接”之外的另一个原因,例如,如果开发人员明确要求webdriver打开一个新选项卡,我将不胜感激。你就是那个人。非常感谢你!请注意,
switch\u to\u window()
已被弃用,并被
switch\u to.window()
可能有用的添加内容所取代-要连续循环浏览所有打开的选项卡,请使用
import itertools,time;对于itertools.cycle中的tab(反转(驱动程序.窗口\处理)):驱动程序.切换到.窗口(tab);time.sleep(2)
@winklerrr答案更新为较新的
开关\u to.window()
,tks!答案中的
test
变量来自哪里?与被接受的答案或一些排名靠前的答案有什么不同?test=tab_列表正如帖子中提到的,解决方案的想法已经在被接受的答案第3项中,我只是认为写下来可以帮助像我这样的用户,没有正式的it教育。直到现在我才意识到“贪婪的秃鹫”在之前的一篇文章中也解释了。。。
   driver.switch_to.window(test[1])
    driver.switch_to.window(test[0])
from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get('https://www.google.com')

driver.execute_script("window.open('');")
time.sleep(5)

driver.switch_to.window(driver.window_handles[1])
driver.get("https://facebook.com")
time.sleep(5)

driver.close()
time.sleep(5)

driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.yahoo.com")
time.sleep(5)

#driver.close()