CentOS7 安装Selenium(使用webdriver_manager自动安装ChromeDriver)

在 CentOS 7 上安装 Selenium 通常涉及几个步骤,包括安装 Python、安装 Selenium 库、安装 WebDriver 以及配置环境。以下是详细的步骤:

1. 安装 Python 和 pip

如果你的系统中还没有安装 Python 和 pip,可以使用以下命令进行安装:

sh 复制代码
sudo yum update -y
sudo yum install -y python3
sudo yum install -y python3-pip

验证安装:

sh 复制代码
python3 --version
pip3 --version

2. 安装 Selenium 库

使用 pip 安装 Selenium:

sh 复制代码
pip3 install selenium

3. 安装 WebDriver

Selenium 需要 WebDriver 来与浏览器进行交互。根据你使用的浏览器,安装相应的 WebDriver。

安装 ChromeDriver
  1. 安装 Google Chrome

    sh 复制代码
    sudo yum install -y wget
    # wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
    # sudo yum localinstall -y google-chrome-stable_current_x86_64.rpm
    # 安装低版本
    wget http://dist.control.lth.se/public/CentOS-7/x86_64/google.x86_64/google-chrome-stable-102.0.5005.115-1.x86_64.rpm
    sudo yum localinstall -y google-chrome-stable-102.0.5005.115-1.x86_64.rpm
  2. 使用 webdriver_manager 来安装 ChromeDriver

python 复制代码
# install_chromedirver.py
import os
import subprocess
import shutil
import platform  # 导入 platform 模块
from webdriver_manager.chrome import ChromeDriverManager

# 安装并获取最新的 ChromeDriver 版本
driver_path = ChromeDriverManager().install()
print(f"ChromeDriver downloaded to: {driver_path}")

def move_chromedriver(driver_path):
    system = platform.system()
    if system in ["Linux", "Darwin"]:
        destination_path = "/usr/local/bin/chromedriver"
    elif system == "Windows":
        destination_path = os.path.join(os.environ['WINDIR'], 'system32', 'chromedriver.exe')
    else:
        raise Exception(f"Unsupported OS: {system}")

    # 确保目标目录存在
    os.makedirs(os.path.dirname(destination_path), exist_ok=True)
    
    # 移动文件并设置权限
    shutil.move(driver_path, destination_path)
    os.chmod(destination_path, 0o755)
    return destination_path

def get_chromedriver_version(driver_path):
    try:
        # 调用命令行工具 chromedriver --version
        output = subprocess.check_output([driver_path, '--version'])
        # 解码输出并获取版本号
        version = output.decode('utf-8').strip()
        return version
    except Exception as e:
        print(f"Error occurred while getting ChromeDriver version: {e}")
        return None

def main():
    print("Moving ChromeDriver to /usr/local/bin or system32...")
    new_driver_path = move_chromedriver(driver_path)
    print(f"ChromeDriver moved to: {new_driver_path}")

    print("Checking ChromeDriver version...")
    chromedriver_version = get_chromedriver_version(new_driver_path)
    if chromedriver_version:
        print(f"ChromeDriver version: {chromedriver_version}")
    else:
        print("Failed to get ChromeDriver version.")

if __name__ == "__main__":
    main()

3. 执行命令安装

bash 复制代码
sudo python install_chromedirver.py

4. 测试 Selenium 安装(无头模式:在某些环境中(例如:无显示器的服务器),需要以无头模式启动 Chrome。)

创建一个 Python 脚本来测试 Selenium 安装是否成功:

python 复制代码
# test_selenium.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")

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

# 测试代码
driver.get("http://www.baidu.com")
print(driver.title)
driver.quit()

运行脚本:

sh 复制代码
python3 test_selenium.py

如果打开了浏览器并打印了页面标题,说明 Selenium 安装成功。

总结

通过以上步骤,应该能够在 CentOS 7 上成功安装并配置 Selenium。这个过程包括安装 Python 和 pip、安装 Selenium 库、安装相应的 WebDriver(如 ChromeDriver 或 GeckoDriver),以及测试配置。

相关推荐
思则变1 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络2 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find3 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取4 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector6 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
q567315236 小时前
Java Selenium反爬虫技术方案
java·爬虫·selenium
Zonda要好好学习6 小时前
Python入门Day2
开发语言·python
Vertira6 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉6 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗6 小时前
黑马python(二十四)
开发语言·python