Electron中启动Selenium应用报错:require is not defined
解决Uncaught ReferenceError: require is not defined问题
你遇到的错误本质是:require是Node.js专属的模块加载语法,浏览器环境不支持;而且selenium-webdriver是为Node.js设计的库,无法直接在浏览器页面中运行。要实现带GUI的Selenium应用,推荐用Electron框架,它能让你同时使用Node.js能力和浏览器页面做GUI。
以下是具体修改方案:
1. 初始化项目并安装依赖
先创建一个新文件夹,打开终端执行:
npm init -y npm install electron selenium-webdriver
2. 调整项目文件结构
最终结构:
你的项目文件夹/ ├── package.json ├── main.js # Electron主进程,负责Selenium逻辑 ├── index.html # 你的GUI页面 └── renderer.js # 渲染进程脚本,处理页面交互
3. 修改各文件内容
main.js(Electron主进程)
const { app, BrowserWindow, ipcMain } = require('electron'); const { Builder, Browser, By, Key, until } = require('selenium-webdriver'); function createWindow() { const mainWindow = new BrowserWindow({ width: 400, height: 300, webPreferences: { nodeIntegration: true, contextIsolation: false } }); mainWindow.loadFile('index.html'); } // 监听渲染进程的启动请求 ipcMain.on('start-selenium', async () => { let driver = await new Builder().forBrowser("chrome").build(); try { await driver.get('https://google.com'); // 等待同意按钮出现再点击 await driver.wait(until.elementLocated(By.id("L2AGLb")), 5000); await driver.findElement(By.id("L2AGLb")).click(); await driver.findElement(By.xpath("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input")).sendKeys("selenium", Key.RETURN); } catch (err) { console.error(err); } }); app.whenReady().then(() => { createWindow(); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
index.html(GUI页面)
<html> <head> <meta charset="UTF-8" /> <title>App</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css"> <script defer src="renderer.js"></script> </head> <body> <div class="align" style="margin: 2rem; text-align: center;"> <h1>App</h1> <button id="start" class="button is-primary">Start</button> </div> </body> </html>
renderer.js(页面交互脚本)
const { ipcRenderer } = require('electron'); // 获取按钮元素 const startButton = document.getElementById('start'); startButton.onclick = () => { // 给主进程发消息,启动Selenium逻辑 ipcRenderer.send('start-selenium'); };
4. 配置package.json脚本
打开package.json,修改scripts部分:
"scripts": { "start": "electron .", "package": "electron-packager . --platform=win32 --arch=x64" // 打包成Windows应用,其他平台调整参数 }
5. 运行和打包
- 启动应用:
npm start - 打包成桌面应用:
npm run package(需要先安装electron-packager:npm install -g electron-packager)
注意:运行前确保你的电脑已经安装了Chrome浏览器,并且ChromeDriver的版本和Chrome版本匹配(selenium-webdriver会自动下载对应驱动,若有问题可手动下载配置)。
内容的提问来源于stack exchange,提问作者elite.dragon
相关产品推荐
相关产品推荐

