Selenium启动Firefox时若已有实例运行就报错,如何处理?
错误原因
Firefox默认禁止同一个用户配置文件同时被多个实例加载,你手动打开的Firefox已经占用了代码中指定的/home/blueray/.mozilla/firefox/5ertyoox.default-release配置文件,Selenium尝试用同一份配置启动新实例时就会触发冲突,报错退出。
可行解决方案
方案1:使用独立的专属配置文件启动Selenium Firefox(推荐,隔离性强)
该方案不会影响你日常使用的Firefox实例,两个实例完全独立,互不干扰:
- 关闭所有运行中的Firefox,终端执行
firefox -ProfileManager唤起配置管理器 - 点击「新建」按钮创建一个专门给Selenium使用的配置(命名可自定义,比如
selenium-special-profile),记录生成的配置文件存储路径 - 修改代码中指定配置路径的部分,替换为新建的专属配置路径即可
修改后的代码片段示例:
options = Options() options.set_preference("dom.popup_maximum", 100) # 替换为你新建的Selenium专属配置的实际路径 options.add_argument("-profile") options.add_argument("/home/blueray/.mozilla/firefox/xxxxxxx.selenium-special-profile") options.page_load_strategy = 'eager'
方案2:Selenium直接连接已经运行的Firefox实例(无需新开实例,可复用现有登录状态)
该方案不需要Selenium启动新的Firefox进程,直接接管你已经打开的Firefox,避免实例冲突:
- 先给正在运行的Firefox开启远程调试功能:打开Firefox设置,搜索「远程调试」,勾选「允许远程调试」;或者关闭现有Firefox后,用
firefox --remote-debugging-port=9222命令启动 - 修改代码逻辑,直接连接本地开启了调试端口的Firefox实例即可
完整修改后代码:
from selenium import webdriver import urllib.parse import time from selenium.webdriver.firefox.options import Options options = Options() options.set_preference("dom.popup_maximum", 100) options.page_load_strategy = 'eager' # 连接本地9222端口的已有Firefox实例 options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") browser = webdriver.Firefox(options=options) with open("google-search-terms.adoc") as fin: for line_no, line in enumerate(fin): line = line.strip() query = urllib.parse.urlencode({'q': line + " site:amazon.com"}) browser.execute_script(f"window.open('https://www.google.com/search?{query}');") time.sleep(5) for x in range(1, len(browser.window_handles)): browser.switch_to.window(browser.window_handles[x]) try: elm = browser.find_elements_by_xpath( '/html/body/div[7]/div/div[9]/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div/div[1]/a/h3') if not elm: elm = browser.find_elements_by_xpath( '/html/body/div[7]/div/div[9]/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div/div/div[1]/a/h3') elm[0].click() except Exception as e: print("Error", str(e))
内容的提问来源于stack exchange,提问作者Ahmad Ismail
相关产品推荐
相关产品推荐

