ubuntu24.04安装selenium、chrome、chromedriver

实验环境:kaggle notebook、colab notebook

1、安装chrome

复制代码
!wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

!sudo dpkg -i google-chrome-stable_current_amd64.deb

!sudo apt-get install -f

!export QT_QPA_PLATFORM=offscreen

!sudo apt-get install -f

!sudo dpkg -i google-chrome-stable_current_amd64.deb

!google-chrome --version

安装字体

复制代码
!sudo apt-get install ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy

2、安装chromedriver

复制代码
!wget https://storage.googleapis.com/chrome-for-testing-public/138.0.7204.183/linux64/chromedriver-linux64.zip

!unzip chromedriver-linux64.zip

!sudo mv chromedriver-linux64 /usr/local/bin

!sudo chmod +x /usr/local/bin/chromedriver-linux64/chromedriver

3、安装selenium

复制代码
!pip install selenium

4、测试脚本(jupyter notebook版,无头浏览器模式)

复制代码
import tempfile
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
#from webdrivermanager_cn import ChromeDriverManager
import time

# 自动下载驱动
#driver_path = ChromeDriverManager().install()

# 创建临时用户数据目录
user_data_dir = tempfile.mkdtemp()

# 设置 Chrome 启动参数
options = Options()
options.add_argument(f"--user-data-dir={user_data_dir}")
options.add_argument("--no-sandbox")          # Linux 通常需要
options.add_argument("--disable-dev-shm-usage")  # Linux 通常需要
options.add_argument("--headless")            # 如不需要图形界面,可添加此项

# 启动浏览器
service = Service(executable_path='/usr/local/bin/chromedriver-linux64/chromedriver')
driver = webdriver.Chrome(service=service, options=options)

# 使用浏览器
driver.get("https://www.baidu.com")
print(driver.title)
time.sleep(3)
#截屏
driver.save_screenshot(filename="baidu.png")
time.sleep(3)

driver.quit()
相关推荐
测试老哥2 小时前
Selenium 使用指南
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
pc大老3 小时前
优化浏览体验:4个设置让Google Chrome更好用!
chrome·google·谷歌浏览器·谷歌·浏览器设置
智能化咨询3 小时前
【Linux】【实战向】Linux 进程替换避坑指南:从理解 bash 阻塞等待,到亲手实现能执行 ls/cd 的 Shell
前端·chrome
霍格沃兹软件测试开发3 小时前
快速掌握Dify+Chrome MCP:打造网页操控AI助手
人工智能·chrome·dify·mcp
Anson Jiang3 小时前
浏览器标签页管理:使用chrome.tabs API实现新建、切换、抓取内容——Chrome插件开发从入门到精通系列教程06
开发语言·前端·javascript·chrome·ecmascript·chrome devtools·chrome插件
文人sec12 小时前
性能测试-jmeter9-逻辑控制器、定时器压力并发
测试工具·jmeter·性能优化·模块测试
学生信的大叔12 小时前
【Python自动化】Ubuntu24.04配置Selenium并测试
python·selenium·自动化
林克爱塞尔达1 天前
Linux入门(二)
linux·运维·chrome
Larry_zhang双栖2 天前
低版本Chrome 内核兼容性问题的优美解决
前端·chrome