python - 在新选项卡中打开链接并在选项卡之间切换(Selenium WebDriver + Python)

标签 python selenium-webdriver

<分区>

我有这样的注释代码:

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 未在新选项卡中打开。 关于它还有其他想法吗?谢谢。

PS:我在 macOS 上。

最佳答案

您可以使用此代码:

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

用于切换:

driver.switch_to_window(driver.window_handles[0])

引用这个Answer .

关于python - 在新选项卡中打开链接并在选项卡之间切换(Selenium WebDriver + Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46425797/

相关文章:

javascript - 为什么javaScript中的这个循环函数不是每次都返回0?我将如何在 python 中做类似的事情?

python - 名称错误 : name 'MainCorridor' is not defined

python - 在 python 中获取 keyerror

python - 为什么 weakref 不支持 Python 中的内置类型?

javascript - 在 django 模板中打开链接内容

java - 如何在不使用文本的情况下从页面中选择内容?

javascript - 为 selenium webdriver 设置特定功能

c# - 使用 .NET Core MSTest 运行单元测试 : "The following TestContainer was not found..."

python - 如何修复 "ImportError: Unable to load EGL library',22,找不到指定的模块”

java - TestNG 多次运行所有类方法,初步使用提供的数据执行@BeforeClass