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

从PHP调用Python Selenium Chrome爬虫报错,求解决方案

解决PHP exec调用Python Selenium脚本时Chrome启动失败的问题

1. 指定Chrome与ChromeDriver的绝对路径

Shell环境的PATH和PHP运行时(通常是web服务器用户,如www-data)的PATH可能不一致,导致找不到Chrome或ChromeDriver。直接在Python脚本里指定绝对路径:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
# 替换为你的Chrome二进制文件绝对路径,可通过Shell命令`which google-chrome`获取
options.binary_location = "/usr/bin/google-chrome"
# 替换为你的ChromeDriver绝对路径,可通过Shell命令`which chromedriver`获取
driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver", options=options)

2. 启用Chrome无头模式并添加必要参数

PHP运行环境通常没有桌面会话,Chrome必须以无头模式启动,同时添加参数规避权限、资源限制:

options.add_argument("--headless=new")  # 新版无头模式,兼容性更强
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")  # 绕过沙箱限制,web服务器用户通常无沙箱权限
options.add_argument("--disable-dev-shm-usage")  # 解决/dev/shm空间不足问题
options.add_argument("--remote-debugging-port=9222")  # 指定固定调试端口,避免冲突

3. 修复权限问题

  • 确保web服务器用户对Chrome、ChromeDriver及脚本目录有读写执行权限:
    sudo chmod +x /usr/bin/google-chrome /usr/local/bin/chromedriver
    sudo chown -R www-data:www-data /path/to/your/python/script
    
  • 检查/tmp目录权限:Chrome会在此创建临时文件,确保权限为drwxrwxrwt,可执行ls -ld /tmp确认。

4. 处理Linux环境下的X服务器依赖

Linux下Chrome依赖X服务器,即使无头模式也可能需要虚拟显示支持:

  • 安装Xvfb:
    sudo apt-get install xvfb  # Debian/Ubuntu系统
    
  • 在PHP的exec命令中用Xvfb-run启动脚本:
    exec("xvfb-run -a python3 /path/to/your/script.py", $output, $return_var);
    
    或者在Python脚本中集成虚拟显示(需先安装pyvirtualdisplay库:pip install pyvirtualdisplay):
    from pyvirtualdisplay import Display
    display = Display(visible=0, size=(1920, 1080))
    display.start()
    
    # 此处放启动driver、爬取页面的代码
    
    display.stop()
    

5. 清理残留的Chrome进程

异常退出可能导致Chrome/ChromeDriver进程残留,占用资源或端口。可以:

  • 在PHP调用脚本前清理进程:
    exec("pkill -f chrome", $output, $return_var);
    exec("pkill -f chromedriver", $output, $return_var);
    
  • 在Python脚本中确保driver正常退出:
    try:
        driver.get("https://www.python.org")
        print(driver.title)
    finally:
        driver.quit()  # 必须用quit()而非close(),确保关闭所有关联进程
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:33:28