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

如何在Linux下以非root用户运行含Selenium的Python脚本?

解决Linux下以非root用户运行Selenium Python脚本的方法

1. 创建普通用户(若未存在)

如果系统还没有合适的普通用户,先创建一个带家目录的用户:

useradd -m selenium_user
passwd selenium_user  # 为该用户设置登录密码

2. 配置权限

确保普通用户能访问脚本、Chrome及ChromeDriver:

  • 给脚本所在目录及文件分配权限:
chown -R selenium_user:selenium_user /path/to/your/script_folder
chmod -R 755 /path/to/your/script_folder
  • 确保Chrome和ChromeDriver对普通用户可执行(默认已开放,若有问题执行):
chmod +x /usr/bin/google-chrome
chmod +x /usr/bin/chromedriver

3. 以普通用户身份运行脚本

两种常用方式:

  • 临时切换用户后运行:
su - selenium_user
cd /path/to/your/script_folder
python3 your_script.py  # 根据实际Python版本调整命令
  • 直接用sudo指定用户运行:
sudo -u selenium_user python3 /path/to/your/script.py

4. 脚本优化(可选)

在无GUI环境运行时,保留headless参数的同时,可添加更稳定的配置项提升兼容性:

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

op = Options()
op.add_argument('--headless=new')  # 新版headless模式,兼容性更好
op.add_argument('--disable-gpu')
op.add_argument('--window-size=1920x1080')

chromedriver = "/usr/bin/chromedriver"
driver = webdriver.Chrome(chromedriver, options=op)

try:
    url = '你的目标URL'
    driver.get(url)
    # 此处添加你的业务逻辑
finally:
    driver.quit()  # 确保脚本结束后关闭浏览器进程

注意:不要使用--no-sandbox参数,这是官方明确不推荐的不安全配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:07:43