开启智能数字体验
Djacore CMS 驱动未来

基于Django 5.2的企业级智能内容管理系统,为千万级数据量设计, 提供安全、高效、可扩展的网站建设与内容管理一体化解决方案

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

:本站 2026-01-06 00:58:37 10

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了。

 

 

本文编辑:admin

更多文章:


使用DRF快速搭建API接口,Django REST Framework ModelViewSet 用法总结

使用DRF快速搭建API接口,Django REST Framework ModelViewSet 用法总结

Django REST Framework ModelViewSet 用法总结1. ModelViewSet 简介ModelViewSet是 Django REST Framework (DRF) 中的一个视图集类,它继承自多个 mixin

2026年3月1日 09:10

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

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

在实操当中有一项目需要使用selenium进行浏览器模拟,但是测试了很多都不行,最后通过了,总一下系统级安装chrome浏览器及驱动这些都不细说了测试项目运行用户:check_user.py建立一个API,使用check_user获取用户,

2026年1月6日 00:58

Django移除模型后的content_type操作

Django移除模型后的content_type操作

旧应用(apps.content.download)的模型虽然已删除,但其在 django_content_type表中的记录仍然存在,与新应用(user_space.apps.download)的记录产生了混淆。您需要清理这些过时的记录。

2025年12月22日 11:36

django.utils中都有哪些功能?django.utils工具都详情的举例说明

django.utils中都有哪些功能?django.utils工具都详情的举例说明

Django 的 django.utils模块是一个“百宝箱”,它提供了大量用于处理日常底层任务的实用工具。下面这个表格汇总了其中一些最常用的工具模块及其核心功能,可以帮助你快速了解其概貌。模块/工具类别主要功能/工具举例简要说明djang

2025年11月27日 22:32

Django 的基于类的视图总结,Django CBV类的详细使用方法整理

Django 的基于类的视图总结,Django CBV类的详细使用方法整理

Django 的基于类的视图(Class-based Views,简称 CBV)通过类的形式封装了常见的 Web 开发模式,提供了清晰的结构和强大的可复用性。下面这个表格汇总了这些核心基类的主要作用和典型应用场景,可以帮助你快速了解其用途。

2025年11月17日 08:52

Django transaction.atomic() 的具体作用和用法?

Django transaction.atomic() 的具体作用和用法?

transaction.atomic()是 Django 中用于管理数据库事务的核心工具,它能确保一系列数据库操作作为一个不可分割的“原子”单元来执行。下面这个表格能帮你快速抓住要点。特性说明核心目标保证一系列数据库操作的原子性(Atomi

2025年10月31日 23:35

django 批量操作的方法有哪些?如何高效的批量更新django内容

django 批量操作的方法有哪些?如何高效的批量更新django内容

Django 提供了多种批量操作方法,能显著提升数据库操作的效率,特别是在处理大量数据时。下面为你梳理这些方法,并说明其适用场景和注意事项。下表总结了主要的批量操作方法及其核心用途:方法类别核心方法主要用途关键特点📦 批量创建bulk_cr

2025年10月31日 23:30

django的分页器以及django分页器中有哪些变量

django的分页器以及django分页器中有哪些变量

Django 的分页器(Paginator)是一个用于管理数据分页的强大工具,它能将大量数据分割成多个页面,并生成相应的导航链接。下面这个表格汇总了 Django 分页器中的核心类及其主要属性和方法,方便你快速了解其构成。组件/类别名称说明

2025年10月20日 10:16

Django get_FOO_display() 方法,Django模型中原生方法总结

Django get_FOO_display() 方法,Django模型中原生方法总结

在Django中有一种方法被称为 ​​get_FOO_display() 方法​​,对模型中定义了 choices选项的字段名的灵活使用方法。在Django中,choices参数用于为模型字段提供一组固定的可选值,它在数据库层面存储简洁的值

2025年10月13日 20:56

django​​字段查找(Field Lookups)总结,django​​查询中指定特定的条件或对字段的处理方法

django​​字段查找(Field Lookups)总结,django​​查询中指定特定的条件或对字段的处理方法

在Django ORM中,双下划线 __后跟的关键词(如 __date、__icontains)被称为​​字段查找(Field Lookups)​​。它们用于在查询中指定特定的条件或对字段进行某种处理。 📊

2025年10月8日 23:07

最近更新

使用DRF快速搭建API接口,Django REST Framework ModelViewSet 用法总结
2026-03-01 09:10:09 浏览:4
宝塔Nginx免费防火墙常用UA防护正则
2026-01-20 00:53:21 浏览:38
django 使用selenium注意事项:Service /usr/local/bin/chromedriver unexpectedly exited. Status code was: 1解决办法
2026-01-06 00:58:37 浏览:10
Django移除模型后的content_type操作
2025-12-22 11:36:29 浏览:6
热门文章

DjancoreCMS打包前操作
2025-05-26 17:58:05 浏览:81
宝塔Nginx免费防火墙常用UA防护正则
2026-01-20 00:53:21 浏览:38
标签列表