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版本完全对应,否则会触发兼容性错误:
- 查看VPS上Chrome的版本:
google-chrome --version
- 下载对应版本的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自动匹配驱动:
- 安装依赖:
pip install webdriver-manager
- 修改驱动初始化代码:
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
相关产品推荐
相关产品推荐

