【问题标题】:Cannot open a newtab in selenium webdriver on Mac OS X无法在 Mac OS X 上的 selenium webdriver 中打开新选项卡
【发布时间】:2017-06-05 17:04:37
【问题描述】:

我应该能够使用代码在 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.execute_script('window.open();')
  • @Andersson 这有效....我不知道为什么。你知道如何切换到新的打开标签。如果我能弄清楚,我会考虑回答的问题。

标签: python macos selenium firefox selenium-webdriver


【解决方案1】:

尝试下面的代码打开新标签并切换到它:

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");')

【讨论】:

  • 非常有帮助。如果您查看我发布的更新而不是切换到最新选项卡,那么还有一个问题,脚本会返回到第一个选项卡。我不知道为什么会这样。
  • 搜索邮件输入框时无需再次切换打开Github。检查更新
  • 我认为你误解了我的问题。我试图在两个不同的选项卡中打开同一个网站两次,并将文本添加到两个不同的字段。
  • 哦...我明白了。试试third_tab = [tab for tab in driver.window_handles if tab not in (current_tab, new_tab)][0]
  • 有效。 Excpet 创建一个新选项卡然后加载网页需要两个单独的命令,否则它无法找到文本字段。
【解决方案2】:

尝试以下代码在 MAC 中打开新标签页:-

String clickOnTabLink = Keys.chord(Keys.COMMAND, "t", Keys.ENTER);
link.sendKeys(clickOnTabLink);

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2012-09-28
    相关资源
    最近更新 更多