首页 > 解决方案 > 如何使用 selenium 打开和管理新标签页

问题描述

我正在尝试使用“https://www.gmail.com”网址打开一个新标签,然后选择一些信息并返回第一页,我正在使用 CTRL + t 命令打开新标签,但是,如何在两个页面之间切换?我的代码片段:

driver.find_elements_by_css_selector('body').send_keys(Keys.CONTROL + "t")

实际代码:

            bot = self.bot

            guids = bot.window_handles()

            time.sleep(2)

            bot.execute_script("window.open()")

            bot.get('https://gmail.com')

            time.sleep(1)

Python 版本 = Python 3.8.5

标签: pythonseleniumwebdriverselenium-chromedriver

解决方案


#current window
    first_tab = bot.window_handles[0]
#create new tab
    bot.execute_script("window.open()")
#move to new tab
    new_tab = bot.window_handles[1]
    bot.switch_to.window(new_tab)
    bot.get('https://gmail.com')
#switch to first tab
    bot.switch_to.window(first_tab)

推荐阅读