从PHP调用Python+Selenium脚本时出现Failed to read marionette port错误
问题:Apache执行Python爬虫脚本时抛出TimeoutException(Failed to read marionette port)
脚本在Ubuntu终端运行正常,但通过PHP调用(Apache执行)时出现TimeoutException: Failed to read marionette port错误,已确认Firefox和Geckodriver具备执行权限,环境版本:Python 3.10.6、Selenium 4.10.0、Firefox 107.0.1、Geckodriver 0.33.0。
相关代码
Python爬虫Geckodriver配置部分
def BUscrap(limit=""): limit=int(limit) print("Capturando nuevos trabajos...") options=webdriver.FirefoxOptions() service = Service(executable_path='/usr/local/bin/geckodriver') options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument(f'--proxy-server={proxy_server_url}') options.add_argument('user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36') driver=webdriver.Firefox(service=service, options=options) driver.implicitly_wait(10)
PHP调用代码
<?php $cmd = escapeshellcmd("./realScrapper.py " .$_POST["ligas"]); if(isset($_POST['ejecutar'])) { echo '<div class="output">'; while (@ ob_end_flush()); $proc = popen($cmd, 'r'); echo '<pre>'; while (!feof($proc)) { echo fread($proc, 4096); @ flush(); } echo '</pre>'; $_POST = array(); echo '</div>'; } ?>
解决方法
明确指定Firefox二进制路径
Apache运行环境可能无法自动定位Firefox安装路径,需在FirefoxOptions中手动设置:options.binary_location = '/usr/bin/firefox' # 可通过终端执行`which firefox`获取实际路径延长Marionette端口等待超时
修改Geckodriver的Service配置,增加启动超时时间:service = Service(executable_path='/usr/local/bin/geckodriver') service.start_timeout = 30 # 将超时时间从默认值延长至30秒也可指定固定Marionette端口:
service = Service(executable_path='/usr/local/bin/geckodriver', service_args=['--marionette-port', '2828'])补充Apache用户的环境变量
Apache默认以www-data用户运行,可能缺少必要环境变量,可在PHP调用时添加:$cmd = escapeshellcmd("export DISPLAY=:0 && ./realScrapper.py " . $_POST["ligas"]);或在Python脚本开头直接设置:
import os os.environ['DISPLAY'] = ':0'调整PHP与Apache的超时设置
脚本执行时间过长可能被提前终止,修改php.ini:max_execution_time = 300 # 设置为300秒或更长时间同时在PHP代码中添加:
set_time_limit(300);验证Apache用户的权限
确保www-data用户拥有访问脚本目录、Geckodriver、Firefox及临时目录的权限:sudo chmod +x /usr/local/bin/geckodriver sudo chown -R www-data:www-data /path/to/your/script/directory确认版本兼容性
虽然当前Geckodriver与Firefox版本理论兼容,若问题仍存在,可尝试升级Geckodriver至对应Firefox版本的最新兼容版。
内容的提问来源于stack exchange,提问作者Arturo Domnico Navarro Riveros
相关产品推荐
相关产品推荐

