You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CentOS7下PHP调用Python的Selenium ChromeDriver启动失败求助

解决PHP调用Selenium ChromeDriver卡住的问题

核心原因及对应解决方案

1. 明确指定Chrome可执行文件路径

PHP运行的系统用户(通常是apache或nginx)无法识别Chrome的默认路径,需在Python代码中手动指定:
修改代码中的ChromeOptions配置:

options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.headless = True
# 替换为你系统中Chrome的实际路径,可通过`which google-chrome`命令获取
options.binary_location = "/usr/bin/google-chrome"
driver = webdriver.Chrome(options=options)

2. 赋予PHP用户足够权限

  • 确保脚本所在目录及截图保存目录对PHP运行用户有读写权限:
    # 若使用Apache,用户为apache;Nginx则替换为nginx
    chown -R apache:apache /path/to/your/script/folder
    chmod -R 755 /path/to/your/script/folder
    

3. 安装Chrome依赖库

CentOS环境下Chrome运行可能缺失系统依赖,执行以下命令补充:

yum install -y libX11 libXext libXtst libXScrnSaver libXdamage libXfixes libXrandr libXcursor mesa-libGL mesa-libEGL

4. 捕获错误日志排查问题

修改Python代码添加异常捕获,将错误信息写入日志文件,便于定位具体问题:

import time
import traceback
from PIL import Image
from selenium import webdriver

try:
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    options.headless = True
    options.binary_location = "/usr/bin/google-chrome"
    driver = webdriver.Chrome(options=options)
    driver.set_window_size(1920, 1080)
    URL = "https://google.com"
    driver.get(URL)
    time.sleep(5)
    driver.save_screenshot('1.png')
    driver.quit()
    im = Image.open( "1.png")
    width, height = im.size
    left = 1
    top = height / 7
    right = 1920
    bottom = height
    im1 = im.crop((left, top, right, bottom))
    im1.save("1.png")
except Exception as e:
    with open("error.log", "w") as f:
        f.write(str(e))
        f.write("\n")
        f.write(traceback.format_exc())

执行PHP调用后,查看生成的error.log获取具体错误信息,针对性修复。

5. 匹配ChromeDriver与Chrome版本

ChromeDriver版本必须和系统中安装的Chrome版本严格对应,版本不匹配会直接导致初始化失败。重新下载对应版本的ChromeDriver替换现有文件,并确保PHP用户可访问该文件。

内容的提问来源于stack exchange,提问作者Hamed Ap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:50:27