无法在Mac OS X上的Selenium WebDriver中打开newtab [英] Cannot open a newtab in selenium webdriver on Mac OS X
问题描述
我应该能够使用代码
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屋!