Python 在新选项卡上打开链接

Python 在新选项卡上打开链接,python,selenium-webdriver,Python,Selenium Webdriver,我需要在新选项卡/窗口中的标记中打开一个链接,在那里做一些事情,然后关闭它 html代码: <body> <a id="uniqueid" href="somelink">I need to open this in a new tab</a> </body> 首先,您希望从“uniqueid”元素获取url: url = element.get_attribute('href') 然后进入该页面

我需要在新选项卡/窗口中的
标记中打开一个链接,在那里做一些事情,然后关闭它

html代码:

<body>
    <a id="uniqueid" href="somelink">I need to open this in a new tab</a>
</body>

首先,您希望从
“uniqueid”
元素获取url:

url = element.get_attribute('href')
然后进入该页面,使用Ctrl-TAB切换到该页面,然后在该页面上执行以下操作:

# Save current window
w0 = drv.window_handles[0]

# Create new window, make it the active tab
drv.execute_script("window.open('" + url + "');")
drv.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
sleep(3)
w1 = drv.window_handles[1]

# Change to the new window
drv.switch_to.window(w1)

# Do something here
之后,如果需要,您可以切换回
w0

drv.switch_to.window(w0)
drv.switch_to.window(w0)