背景
最近遇到个问题,需要将 html 批量转换为 markdown,尝试过很多转换库结果并不理想,发现通过复制粘贴的方式效果十分不错。(mac,从chrome浏览器,复制到 typora 中)
go
的 github.com/go-vgo/robotgo
库可以用来做自动化,本例中主要使用其模拟键盘输入robotgo.KeyTap("a", "command")
参考代码
package main
import (
"fmt"
"os/exec"
"github.com/go-vgo/robotgo"
)
func main() {
dir := "/Users/XXX/Documents"
pathArr := []string{
"index.html",
}
robotgo.KeySleep = 1000 //每个快捷键中间间隔 1 秒,保证快捷键正确使用
for _, v := range pathArr {
html := fmt.Sprintf("%s/%s", dir, v)//完整html链接
fmt.Println(html)
md := fmt.Sprintf("%smd/%s.md", dir, v) //md
fmt.Println(md)
cmd := exec.Command("open", html) //此处需要设置html默认打开工具为chrome
cmd.Run()
robotgo.Sleep(5) //保证打开(自动化工具未能识别当前是否打开,此处利用长时间 sleep 保证正常打开)
robotgo.KeyTap("a", "command") //快捷键 command+a 全选
robotgo.KeyTap("c", "command") //快捷键 command+c 拷贝
robotgo.KeyTap("w", "command") //快捷键 command+w 关闭当前标签
cmd2 := exec.Command("open", md) //需要设置默认 markdown 打开工具为 typora
cmd2.Run()
robotgo.Sleep(5)
robotgo.KeyTap("a", "command") //快捷键 command+a 全选
robotgo.KeyTap("v", "command") //快捷键 command+c 拷贝
robotgo.KeyTap("q", "command") //快捷键 command+q 关闭
}
}