【发布时间】:2016-11-15 20:48:22
【问题描述】:
打开 Chrome 和新标签页:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
url = 'http://stackoverflow.com/'
driver = webdriver.Chrome('path_to_chromedriver.exe')
driver.get(url)
driver.maximize_window()
# open new tab using JavaScript. Focus goes to tab no.2 (new tab)
driver.execute_script("window.open('http://youtube.com/');")
# switch to tab no.1 and go to URL. Focus stays on tab no.2 - how to focus tab no.1?
driver.switch_to.window(driver.window_handles[0])
driver.get('http://google.com/')
在 Python 2.7.11 中使用 Selenium 我在 chrome 中打开 两个标签。我可以访问单个标签(转到新 URL),但我无法专注于所选标签。例如,当我打开一个新标签时,它会成为焦点。当我使用driver.switch_to.window(driver.window_handles[0]) 选择第一个选项卡并尝试driver.get('http://google.com/') 时,它会加载新的 URL,但是看着我的屏幕,我目前仍然只能看到第二个选项卡。在这种情况下,我想查看第一个标签 (Google)
我尝试发送用户输入,但它既不能打开新标签,也不能在标签之间切换:
actions = ActionChains(driver)
actions.send_keys(Keys.LEFT_CONTROL + Keys.TAB)
actions.perform()
或
driver.find_element_by_tag_name('body').send_keys(Keys.LEFT_CONTROL + Keys.TAB)
【问题讨论】:
-
为什么不先在 Selenium IDE 中尝试,然后导出到
Python 2/unittest/WebDriver?然后,查看生成的代码,您可能会知道自己做错了什么。请注意,Selenium IDE 是 FireFox 的一个插件,但在两个浏览器中处理选项卡是相似的。