问题
I should be able to open a new tab in selenium for python using the code
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')
But no new tab opens, and no error message appears (http://stackoverflow.com/ does load).
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.
Updated to include answers
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')
回答1:
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')
You can use driver.close()
to close new tab and driver.switch_to.window(current_tab)
to switch back to initial tab
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");')
回答2:
Try below code to open new tab in MAC:-
String clickOnTabLink = Keys.chord(Keys.COMMAND, "t", Keys.ENTER);
link.sendKeys(clickOnTabLink);
来源:https://stackoverflow.com/questions/44374026/cannot-open-a-newtab-in-selenium-webdriver-on-mac-os-x