如何用Lua实现简单自动化?尝试luacom等库未获成功
Lua实现Chrome自动化搜索的可行方案
Windows平台
- 使用
luasendinput库实现键盘输入模拟,配合系统命令启动Chrome:- 通过LuaRocks安装库:
luarocks install luasendinput - 示例脚本:
-- 启动Chrome并打开空白页 os.execute('start chrome.exe "about:blank"') -- 等待Chrome加载完成(可根据设备性能调整等待时长) os.execute('timeout /t 2 /nobreak > nul') local sendinput = require("sendinput") -- 输入搜索内容 sendinput.send("hello world") -- 模拟回车提交搜索 sendinput.send("\\n") - 通过LuaRocks安装库:
Linux平台
- 借助
xdotool工具(需提前安装:sudo apt install xdotool),通过Lua调用系统命令完成操作:-- 启动Chrome os.execute('google-chrome-stable "about:blank" &') -- 等待程序启动 os.execute('sleep 2') -- 激活Chrome窗口并执行输入 os.execute('xdotool search --onlyvisible --name "Google Chrome" windowactivate') os.execute('xdotool type "hello world"') os.execute('xdotool key Return')
macOS平台
- 利用系统自带的AppleScript,通过Lua调用完成自动化:
local applescript_code = [[ tell application "Google Chrome" activate make new window set URL of active tab of front window to "https://www.google.com" delay 1 tell application "System Events" keystroke "hello world" keystroke return end tell end tell ]] os.execute('osascript -e "' .. applescript_code .. '"')
注意事项
- 确保对应依赖已安装:Windows需安装
luasendinput,Linux需安装xdotool,macOS无需额外安装工具 - 等待时间需根据设备性能调整,避免Chrome未完全启动就执行输入操作
- 若Chrome路径非默认,需在启动命令中指定完整可执行文件路径
内容的提问来源于stack exchange,提问作者oruancss
相关产品推荐
相关产品推荐

