【问题标题】:Selenium in Python switch and focus tabPython 中的 Selenium 切换和焦点选项卡
【发布时间】: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 的一个插件,但在两个浏览器中处理选项卡是相似的。

标签: python selenium tabs


【解决方案1】:

我知道它来的有点晚,但以后可能对我有用
使用 Selenium 2(它也支持 Python 2.7),这对我有用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2017-04-20
    • 2018-12-15
    • 1970-01-01
    • 2012-09-25
    • 2016-11-14
    相关资源
    最近更新 更多