Selenium无法打开目标网站问题求助(Firefox/Ubuntu环境)
问题分析与解决
核心错误:Service对象配置错误
你代码里的service实例把executable_path设成了Firefox二进制文件路径,这完全错误——Service需要传入的是Geckodriver的路径,而非浏览器本身的路径,这是导致浏览器启动后无法正常加载网页的关键原因。
修正后的代码
from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep # Snap安装的Firefox和Geckodriver路径 firefox_bin = "/snap/firefox/current/usr/lib/firefox/firefox" geckodriver_bin = "/snap/firefox/current/usr/lib/firefox/geckodriver" options = webdriver.FirefoxOptions() options.add_argument('--headless') options.binary_location = firefox_bin # 此处传入Geckodriver路径,而非Firefox路径 service = webdriver.FirefoxService(executable_path=geckodriver_bin) browser = webdriver.Firefox(service=service, options=options) browser.get("https://univirtus.uninter.com/ava/web/#/") sleep(3) # 新增异常捕获,避免元素找不到时直接崩溃 try: ru = browser.find_element(By.ID, "ru") ru.send_keys("login_example") except Exception as e: print(f"操作出错:{e}") browser.quit()
加载个人Firefox配置文件的方法
Snap安装的Firefox,个人配置文件目录不在默认的~/.mozilla/firefox/,而是位于~/snap/firefox/common/.mozilla/firefox/下。找到你实际的配置文件夹(通常是一串字符加.default的命名),然后在options中添加:
# 替换为你自己的配置文件夹路径 profile_path = "/home/你的用户名/snap/firefox/common/.mozilla/firefox/xxxxxx.default" options.add_argument(f'-profile {profile_path}')
注意:无头模式下加载个人配置容易出现兼容性问题,测试阶段建议先移除--headless参数。
内容的提问来源于stack exchange,提问作者S.U.S
相关产品推荐
相关产品推荐

