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

Ubuntu 22.04 VPS运行Selenium脚本报AttributeError问题求助

解决Ubuntu 22.04 VPS上Selenium的AttributeError问题

出现AttributeError: 'Service' object has no attribute 'process'的核心原因是本地与VPS的Selenium版本不一致,新版Selenium已弃用直接传入executable_path的初始化方式,改用Service类管理驱动程序。以下是具体解决步骤:

一、调整代码适配新版Selenium

将原代码中Chrome驱动的初始化逻辑,改为使用Service类实现:

修改后的完整代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service  # 新增导入Service类
import time
from bs4 import BeautifulSoup as bs4

import discord
from discord.ext import commands
   
def get_html_source(url: str):
    chrome_driver_binary = '/home/romik/Projects/hasuki_bot/chromedriver'
    options = Options()
    options.add_argument("--start-maximized") # 最大化窗口启动浏览器
    options.add_argument("--no-sandbox") # 绕过OS安全模型
    options.add_argument("--disable-dev-shm-usage") # 解决资源限制问题
    options.add_argument("--headless=new")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    
    # 改用Service类初始化驱动
    service = Service(executable_path=chrome_driver_binary)
    driver = webdriver.Chrome(service=service, options=options)
    
    driver.get(url)
    try:
        with open("source-page.html", "w", encoding="utf-8") as file:
            time.sleep(10)
            file.write(driver.page_source)
    except Exception as ex:
        print(ex)
    finally:
        driver.close()
        driver.quit()

if __name__ == "__main__":
    get_html_source("https://ubuntu.com/")

二、确保ChromeDriver与Chrome版本匹配

VPS上的Chrome浏览器版本必须和ChromeDriver版本完全对应,否则会触发兼容性错误:

  1. 查看VPS上Chrome的版本:
google-chrome --version
  1. 下载对应版本的ChromeDriver,替换现有文件后赋予执行权限:
chmod +x /home/romik/Projects/hasuki_bot/chromedriver

三、检查VPS是否安装Chrome浏览器

如果VPS未安装Chrome,执行以下命令安装稳定版:

sudo apt update
sudo apt install google-chrome-stable

可选:用webdriver-manager自动管理驱动

若不想手动维护ChromeDriver版本,可安装webdriver-manager自动匹配驱动:

  1. 安装依赖:
pip install webdriver-manager
  1. 修改驱动初始化代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager  # 新增导入
from selenium.webdriver.chrome.service import Service

# ...其他代码不变...

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)

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

相关产品推荐
方舟 Agent Plan

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

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