我应该能够使用代码在 selenium 中为 python 打开一个新选项卡
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/ 加载)。
请注意,我使用 Keys.COMMAND + 't' 因为我在 OS X 上运行代码。
我不知道是什么导致了像这样的帖子 one , 表示我的代码应该可以工作。
已更新以包含答案
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')
请您参考如下方法:
尝试以下代码打开新标签并切换到它:
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) 切换回初始标签页
另请注意,您可以将要在新选项卡中打开的页面 URL 作为参数传递给 window.open(),例如:
driver.execute_script('window.open("https://google.com");')
