远程Ubuntu(EC2)服务器Selenium仅登录可用,登出报错求助
解决Crond启动Selenium ChromeDriver登出后报错的问题
问题核心
登录服务器时脚本正常运行,登出后报错Message: Service /usr/bin/chromedriver unexpectedly exited. Status code was: 1,本质是crontab执行环境与用户登录shell的环境差异,再加上代码中冗余的虚拟显示配置引发冲突。
具体修复步骤
1. 修正Python脚本冗余配置
Chrome的--headless模式无需虚拟显示,同时使用pyvirtualdisplay会导致资源冲突,还要补上原代码遗漏的time模块:
import sys import time from seleniumwire import webdriver from selenium.webdriver.common.by import By def play(test_duration, address): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--headless=new") # 新版headless兼容性更强 chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--incognito") # 指定有权限的临时目录,避免权限报错 chrome_options.add_argument("--user-data-dir=/tmp/chrome_user_data") # 解决/dev/shm空间不足导致的进程退出问题 chrome_options.add_argument("--disable-dev-shm-usage") # 移除所有pyvirtualdisplay相关代码 driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=chrome_options) driver.get(address) play_btn = driver.find_element(By.XPATH, '/html/body/app-root/div/div[1]/button[1]') send_stats_btn = driver.find_element(By.XPATH, '/html/body/app-root/div/div[1]/button[2]') play_btn.click() time.sleep(test_duration) send_stats_btn.click() driver.quit() # quit会关闭所有窗口并终止进程,无需额外close if __name__ == '__main__': test_duration = int(sys.argv[1]) address = sys.argv[2] play(test_duration, address)
2. 优化Crontab配置
crontab的@reboot任务无需手动设置DISPLAY,同时指定完整PATH并添加日志输出方便排查:
@reboot PATH=/usr/local/bin:/usr/bin:/bin && nohup /usr/bin/python3 /home/ubuntu/test/play/client.py 60 http://192.162.2.2:8080 > /home/ubuntu/test/play/cron_log.txt 2>&1 &
- 直接指定完整PATH,避免crontab默认环境变量不足的问题
- 将标准输出和错误输出重定向到日志文件,方便后续定位问题
3. 验证依赖与权限
- 检查Chrome与chromedriver版本是否匹配:运行
chromedriver --version和google-chrome --version,确保版本一致,版本不匹配会直接导致启动失败 - 确保当前用户对
/tmp目录有读写权限,Chrome会自动创建/tmp/chrome_user_data目录
4. 测试配置效果
无需重启服务器,直接模拟crontab的非登录环境测试脚本:
env -i PATH=/usr/local/bin:/usr/bin:/bin /usr/bin/python3 /home/ubuntu/test/play/client.py 60 http://192.162.2.2:8080
如果运行无报错,说明配置生效。
内容的提问来源于stack exchange,提问作者ADL
相关产品推荐
相关产品推荐

