在新标签页中打开链接并在标签页之间切换(Selenium WebDriver + Python) [英] Opening link in the new tab and switching between tabs (Selenium WebDriver + Python)

查看:1168
本文介绍了在新标签页中打开链接并在标签页之间切换(Selenium WebDriver + Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码并带有注释:

I have such code with comments:

import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys


browser = webdriver.Chrome()
browser.get("https://www.google.com?q=python#q=python")
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: 
browser.find_element_by_class_name("rc"))
first_link = first_result.find_element_by_tag_name("a")

# Save the window opener (current window, do not mistake with tab... 
not the same).
main_window = browser.current_window_handle

# Open the link in a new tab by sending keystrokes on the element.
first_link.send_keys(Keys.COMMAND + "t")

# Switch tab to the new tab, which we will assume is the next one on 
the right and put focus.
browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND + 
Keys.NUMPAD2)

# Close current tab.
browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND + "w")

# Put the focus on the current window which will be the window opener.
browser.switch_to.window(main_window)

但是它不起作用(脚本已挂起)-first_link不在新选项卡中打开. 还有其他想法吗?谢谢.

But it does not work (the script is hanging) -- first_link is not opening in the new tab. Any other thoughts about it? Thanks.

PS:我在macOS上.

PS: I am on the macOS.

推荐答案

您可以使用以下代码:

driver.execute_script("window.open('http://google.com', 'new_window')")

用于切换:

driver.switch_to_window(driver.window_handles[0])

请参阅答案.

这篇关于在新标签页中打开链接并在标签页之间切换(Selenium WebDriver + Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆