无法在Mac OS X上的Selenium WebDriver中打开newtab [英] Cannot open a newtab in selenium webdriver on Mac OS X

查看:80
本文介绍了无法在Mac OS X上的Selenium WebDriver中打开newtab的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该能够使用代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')

但是不会打开任何新标签,也不会出现错误消息( http://stackoverflow.com/会加载).

But no new tab opens, and no error message appears (http://stackoverflow.com/ does load).

请注意,由于我在OS X上运行代码,因此我使用的是 Keys.COMMAND +'t'.

Note that I am using Keys.COMMAND + 't' because I am running the code on OS X.

我不知道是什么引起了这个问题,就像这样的帖子

I have no idea what is causing the issue as posts like this one, indicate that my code should work.

已更新为包含答案

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

current_tab = driver.current_window_handle
driver.execute_script('window.open();')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
driver.get("http://github.com")
inputElement = driver.find_element_by_id("user[login]")
inputElement.send_keys('1')

current_tab = driver.current_window_handle
driver.execute_script('window.open();')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
driver.get("http://github.com")
inputElement = driver.find_element_by_id("user[email]")
inputElement.send_keys('2')

推荐答案

尝试以下代码以打开新标签页并切换到该标签页:

Try below code to open new tab and switch to it:

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

current_tab = driver.current_window_handle
driver.execute_script('window.open("http://github.com");')
new_tab = [tab for tab in driver.window_handles if tab != current_tab][0]
driver.switch_to.window(new_tab)
inputElement = driver.find_element_by_id("user[login]")
inputElement.send_keys('1')

driver.execute_script('window.open("http://github.com");')
third_tab = [tab for tab in driver.window_handles if tab not in (current_tab, new_tab)][0]
driver.switch_to.window(third_tab)
inputElement = driver.find_element_by_id("user[email]")
inputElement.send_keys('2')

您可以使用 driver.close()关闭新标签页,并使用 driver.switch_to.window(current_tab)切换回初始标签页

You can use driver.close() to close new tab and driver.switch_to.window(current_tab) to switch back to initial tab

还请注意,您可以传递要在新选项卡中打开的页面 URL 作为 window.open()的参数,例如:

Also note that you can pass page URL you want to open in new tab as argument to window.open() like:

driver.execute_script('window.open("https://google.com");')

这篇关于无法在Mac OS X上的Selenium WebDriver中打开newtab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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