我们开发了一个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])
关闭多余的标签后,我可以在视频中看到我的标签。
一些可能的方法:
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])
它不起作用,我认为它不会切换选项卡,因为在视频[ app.crossbrowsertesting.com/public/id7ed71371078e09/selenium/… ]中,我看到活动选项卡是相同的。
@Uri不太容易通过视频分析行为。我用另一种可能的方法更新了答案
@Uri用什么方法解决了您的问题?
我认为,如果第二个选项卡具有文本输入,而硒输入文本,至少在我的情况下,这种方法将行不通。
我在使用新标签时遇到了麻烦,这种方法节省了一天的时间
driver.switch_to_window(driver.window_handles[1])