【问题标题】:How to use a running instance of Firefox with Selenium如何使用 Selenium 运行的 Firefox 实例
【发布时间】:2016-11-04 20:22:15
【问题描述】:

我正在运行 Ubuntu 14.04、Firefox 49.0.2、Python 3.4.3 和 Selenium 3.0.1

我想使用 Selenium 自动化一些浏览器功能,而不是做任何网站测试。如何修改下面的简单登录脚本以使用在我的桌面上运行的 Firefox 实例,而不是打开一个新的 Firefox 窗口?

# login_yahoo_mail.py

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get('http://mail.yahoo.com/?.intl=us')
enter_email = driver.find_element_by_id('login-username')
enter_email.clear()
enter_email.send_keys('cleanman2@yahoo.com')
next_button = driver.find_element_by_id('login-signin')
next_button.click()
enter_password = WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID, 'login-passwd')))
enter_password.send_keys('dumba$$yahoo!^!&')
signin_button = driver.find_element_by_id('login-signin')
signin_button.click()

谢谢,吉姆

【问题讨论】:

  • 如果目的不是为了测试,有更简单的方法可以直接使用 javascript 在已经打开的实例上自动执行浏览器功能,例如 Greasemonkey。
  • 我已经很久没有使用过 javascript 或 Greasemonkey 了,现在也不想重新使用它们。如果可能的话,我更喜欢使用 Python。
  • 在有人告诉我之前,我刚刚更改了密码。我不得不重新粘贴代码,第二次忘记输入登录信息。愚蠢的错误,我很抱歉。
  • 我在问这个问题之前看着他们,他们没有帮助我。他们谈论远程服务器、会话 ID 和 Java 补丁。我正在尝试确定是否可以使用在我的桌面上运行的 Firefox。如果我打开一个 Firefox 窗口,我认为此时没有要附加的会话 ID,也许我错了。

标签: selenium firefox python-3.4


【解决方案1】:

'Selenium 4' 是可能的。

每个窗口都有一个唯一标识符,该标识符在单个会话中保持不变。您可以使用以下方法获取当前窗口的窗口句柄: driver.current_window_handle

driver = webdriver.Firefox()

# Store the ID of the original window
original_window = driver.current_window_handle

# Opens a new tab and switches to new tab
driver.switch_to.new_window('tab')

# Opens a new window and switches to new window
driver.switch_to.new_window('window')

#Close the tab or window
driver.close()

#Switch back to the old tab or window
driver.switch_to.window(original_window)

我还没有尝试过,但由于 Webdriver 不知道操作系统的焦点在哪里,你可以通过这些选项找到你想要的方式。

更多:Windows and tabs handle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多