Python中的Selenium切换和焦点选项卡

时间:2016-11-15 20:48:22

标签: python selenium tabs

打开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中打开两个标签。我可以访问单个标签(转到新网址),但我无法关注所选标签。例如,当我打开一个新选项卡时,它会成为焦点。当我使用driver.switch_to.window(driver.window_handles[0])选择第一个标签并尝试driver.get('http://google.com/')时,它会加载新网址,但查看我的屏幕,我目前仍然只能看到第二个标签。在这种情况下,我想查看第一个标签(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)

1 个答案:

答案 0 :(得分:1)

我知道它来得有点晚,但是以后可能对我有用
使用 Selenium 2 (它也支持Python 2.7),这对我来说很成功

main_tab = browser.current_window_handle
something_to_open_your_new_tab()
browser.switch_to_window(main_tab)