温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How do I switch to the active tab in Selenium?
google-chrome-extension python selenium

python - 如何在Selenium中切换到活动选项卡?

发布于 2020-04-04 10:51:06

我们开发了一个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 not visible,原因是,因为在新选项卡(由扩展名打开)中,“登录”不可见(我认为仅在命令后才打开新选项卡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])

关闭多余的标签后,我可以在视频中看到我的标签。

查看更多

提问者
Uri
被浏览
63
808 2020-03-24 15:34

一些可能的方法:

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

self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

2-使用ActionsChains(CONTROL + TAB)在选项卡之间切换

actions = ActionChains(self.driver)      
actions.key_down(Keys.CONTROL).key_down(Keys.TAB).key_up(Keys.TAB).key_up(Keys.CONTROL).perform()

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])