django 使用selenium注意事项:Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 1解决办法

在实操当中有一项目需要使用selenium进行浏览器模拟,但是测试了很多都不行,最后通过了,总一下
系统级安装chrome浏览器及驱动
这些都不细说了
测试项目运行用户:check_user.py
建立一个API,使用check_user获取用户,大体看一下用户,后期发现这个是没有必要的,因web运行环境和系统运行环境是不一样的,
import os
import pwd
from django.http import HttpResp***e
def check_user(request):
"""检查当前运行用户"""
uid = os.getuid()
euid = os.geteuid()
try:
user_info = pwd.getpwuid(uid)
effective_user = pwd.getpwuid(euid)
result = f"""
当前用户信息:
用户名:{user_info.pw_name}
用户ID:{uid}
有效用户名:{effective_user.pw_name}
有效用户ID:{euid}
用户目录:{user_info.pw_dir}
Shell:{user_info.pw_shell}
"""
return HttpResp***e(result)
except Exception as e:
return HttpResp***e(f"获取用户信息失败:{str(e)}")
测试系统运行selenium情况
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.opti*** import Opti***
import time
def test_selenium_full():
print("=== 完整Selenium测试开始 ===")
# Chrome配置
chrome_opti*** = Opti***()
chrome_opti***.add_argument("--headless=new")
chrome_opti***.add_argument("--no-sandbox")
chrome_opti***.add_argument("--disable-dev-shm-usage")
chrome_opti***.add_argument("--disable-gpu")
# 服务配置
service = Service(
executable_path="/usr/local/bin/chromedriver",
service_log_path="/tmp/chromedriver_full_test.log"
)
try:
# 启动浏览器
print("正在启动ChromeDriver...")
driver = webdriver.Chrome(service=service, opti***=chrome_opti***)
print("✓ ChromeDriver启动成功")
# 访问测试页面
print("正在访问测试页面...")
driver.get("http://www.example.com")
print(f"✓ 页面访问成功,标题: {driver.title}")
# 执行JavaScript测试
print("正在执行JavaScript测试...")
result = driver****cute_script("return navigator.userAgent;")
print(f"✓ UserAgent: {result}")
# 关闭浏览器
driver.quit()
print("✓ 浏览器正常关闭")
print("=== 完整Selenium测试结束 ===")
return True
except Exception as e:
print(f"✗ 测试失败: {str(e)}")
print("请检查日志文件: /tmp/chromedriver_full_test.log")
return False
if __name__ == "__main__":
success = test_selenium_full()
exit(0 if success else 1)
终端运行
cd 到对应的路径
python test_selenium_full.py
(ghst) root@VM-0-6-debian:/www/wwwroot/ghst/soogor# python test_selenium_full.py
=== 完整Selenium测试开始 ===
正在启动ChromeDriver...
✓ ChromeDriver启动成功
正在访问测试页面...
✓ 页面访问成功,标题: 百度一下,你就知道
正在执行JavaScript测试...
✓ UserAgent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/143.0.0.0 Safari/537.36
✓ 浏览器正常关闭
=== 完整Selenium测试结束 ===这就说明系统环境没有问题的,然后我们测试django下的情况
测试django selenium 运行
def get_chrome_opti***_for_web():
"""为Web环境优化的Chrome配置"""
from selenium.webdriver.chrome.opti*** import Opti***
chrome_opti*** = Opti***()
# 基础配置
chrome_opti***.add_argument("--headless=new")
chrome_opti***.add_argument("--no-sandbox")
chrome_opti***.add_argument("--disable-dev-shm-usage")
# Web环境特定优化
chrome_opti***.add_argument("--disable-gpu")
chrome_opti***.add_argument("--remote-debugging-port=9222")
# 内存和资源优化
chrome_opti***.add_argument("--disable-setuid-sandbox")
chrome_opti***.add_argument("--disable-seccomp-filter-sandbox")
# 指定用户数据目录(避免权限冲突)
import tempfile
user_data_dir = tempfile.mkdtemp(prefix='chrome_web_')
chrome_opti***.add_argument(f"--user-data-dir={user_data_dir}")
# 避免自动化检测
chrome_opti***.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_opti***.add_experimental_option('useAutomationExtension', False)
return chrome_opti***
def test_selenium_full_in_django():
"""在Django环境中运行的Selenium测试"""
import os
import logging
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.opti*** import Opti***
logger = logging.getLogger(__name__)
print("=== Django环境Selenium测试开始 ===")
try:
# 记录环境信息
logger.info(f"Django环境用户: {os.getlogin()}")
logger.info(f"工作目录: {os.getcwd()}")
logger.info(f"PATH: {os.environ.get('PATH', '未设置')}")
# 使用Web环境优化的配置
chrome_opti*** = get_chrome_opti***_for_web()
# 服务配置
service = Service(
executable_path="/usr/local/bin/chromedriver",
service_log_path="/tmp/chromedriver_django.log",
service_args=["--verbose", "--log-level=ALL"]
)
# 启动浏览器
print("正在启动ChromeDriver...")
driver = webdriver.Chrome(service=service, opti***=chrome_opti***)
print("✓ ChromeDriver启动成功")
# 访问测试页面
print("正在访问测试页面...")
driver.get("http://www.example.com")
print(f"✓ 页面访问成功,标题: {driver.title}")
# 执行JavaScript测试
print("正在执行JavaScript测试...")
result = driver****cute_script("return navigator.userAgent;")
print(f"✓ UserAgent: {result}")
# 关闭浏览器
driver.quit()
print("✓ 浏览器正常关闭")
print("=== Django环境Selenium测试结束 ===")
return True
except Exception as e:
print(f"✗ 测试失败: {str(e)}")
logger.error(f"Selenium测试失败: {str(e)}", exc_info=True)
# 检查日志文件
try:
with open("/tmp/chromedriver_django.log", "r") as f:
log_content = f.read()
if log_content:
print("详细日志内容:")
print(log_content[-1000:]) # 显示最后1000字符
except:
print("无法读取日志文件")
return False
找一个API将test_selenium_full_in_django方法引入
print(f"调用Django环境优化的Selenium测试")
# 使用专门为Django环境优化的函数
success = test_selenium_full_in_django()
if success:
print("✅ Selenium在Django环境中测试成功")
# 继续您的业务逻辑
else:
print("❌ Selenium在Django环境中测试失败")
# 处理失败情况
=== Django环境Selenium测试开始 ===
正在启动ChromeDriver...
✗ 测试失败: Message: Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 1
Selenium测试失败: Message: Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 1
Traceback (most recent call last):
File "/www/wwwroot/ghst/soogor/./caiji/views/api_views.py", line 1650, in test_selenium_full_in_django
driver = webdriver.Chrome(service=service, opti***=chrome_opti***)
File "/www/server/pyporject_evn/soogor/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__
super().__init__(
File "/www/server/pyporject_evn/soogor/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 60, in __init__
self.service.start()
File "/www/server/pyporject_evn/soogor/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 109, in start
self.assert_process_still_running()
File "/www/server/pyporject_evn/soogor/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 122, in assert_process_still_running
raise WebDriverException(f"Service {self._path} unexpectedly exited. Status code was: {return_code}")
selenium.common.excepti***.WebDriverException: Message: Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 1虽然分析多种原因有可能造成这种情况,但一般正常的环境下是环境变量问题,所以我们要为django项中运行chrome建立环境变量
def setup_selenium_environment():
"""为Selenium设置运行环境"""
import os
# 设置关键环境变量
os.environ['HOME'] = '/home/www'
os.environ['TMPDIR'] = '/tmp'
# 确保PATH包含必要的目录
current_path = os.environ.get('PATH', '')
if '/usr/local/bin' not in current_path:
os.environ['PATH'] = f'/usr/local/bin:/usr/bin:{current_path}'
完整代码如下:
print(f"🖥️ 启动浏览器模拟: {url}")
setup_selenium_environment()
try:
# 1. 基础Chrome配置(服务器环境优化)
chrome_opti*** = Opti***()
chrome_opti***.add_argument("--headless=new")
chrome_opti***.add_argument("--no-sandbox")
chrome_opti***.add_argument("--disable-dev-shm-usage")
chrome_opti***.add_argument("--incognito")
# 2. 使用您手动安装的ChromeDriver路径
from selenium.webdriver.chrome.service import Service
# 直接指定您安装的路径
chromedriver_path = "/usr/local/bin/chromedriver"
service = Service(
executable_path=chromedriver_path,
service_log_path="/tmp/chromedriver.log", # 指定日志文件路径
service_args=["--verbose"] # 启用所有级别的详细日志
)
# 3. 初始化浏览器驱动
try:
driver = webdriver.Chrome(service=service,
opti***=chrome_opti***)
print("ChromeDriver启动成功")
except Exception as e:
print(f"启动失败: {str(e)}")
# 4. 设置超时时间
driver.set_page_load_timeout(config.get('timeout', 30))
try:
# 5. 访问页面
print(f"🌐 正在访问: {url}")
driver.get(url)
except Exception as e:
driver.quit()
raise e
except Exception as e:
error_msg = f"❌ 浏览器启动失败: {str(e)}"
print(error_msg)
return None, error_msg经此处理后,终于可以在django当中使用selenium了。
更多文章:
使用DRF快速搭建API接口,Django REST Framework ModelViewSet 用法总结
2026年3月1日 09:10
django.utils中都有哪些功能?django.utils工具都详情的举例说明
2025年11月27日 22:32
Django 的基于类的视图总结,Django CBV类的详细使用方法整理
2025年11月17日 08:52
Django transaction.atomic() 的具体作用和用法?
2025年10月31日 23:35
django 批量操作的方法有哪些?如何高效的批量更新django内容
2025年10月31日 23:30
Django get_FOO_display() 方法,Django模型中原生方法总结
2025年10月13日 20:56
django字段查找(Field Lookups)总结,django查询中指定特定的条件或对字段的处理方法
2025年10月8日 23:07





















