前几天发过帖子用python写的批量下载公众号话题音频工具 ,这次国庆学golang重写了下,代码:
[Asm] 纯文本查看 复制代码 package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
)
func Exists(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func InArray(items []string, item string) bool {
for _, eachItem := range items {
if eachItem == item {
return true
}
}
return false
}
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Print("错误信息:")
fmt.Println(err)
}
}()
var url string
fmt.Print("输入话题地址:")
fmt.Scanln(&url)
if len(url) == 0 {
panic("话题地址为空")
}
client := &http.Client{}
reqest, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
response, _ := client.Do(reqest)
defer response.Body.Close()
bResp, _ := io.ReadAll(response.Body)
content := string(bResp)
var voiceids = regexp.MustCompile(`data-voiceid="(.*)"`).FindAllStringSubmatch(content, -1)
var titles = regexp.MustCompile(`data-title="(.*)" data-voiceid`).FindAllStringSubmatch(content, -1)
fileName := "wechat_topic_audio_list.txt"
// fmt.Print(voiceids, titles)
fileContent, _ := ioutil.ReadFile(fileName)
var voice_urls = regexp.MustCompile(`\n`).Split(string(fileContent), -1)
// fmt.Print(voice_urls)
var f2 *os.File
for k, v := range voiceids {
if InArray(voice_urls, "https://res.wx.qq.com/voice/getvoice?mediaid="+v[1]) {
fmt.Println("已经下载过音频:" + titles[k][1])
continue
}
res, _ := http.Get("https://res.wx.qq.com/voice/getvoice?mediaid=" + v[1])
f, _ := os.Create(titles[k][1] + ".mp3")
io.Copy(f, res.Body)
if Exists(fileName) {
f2, _ = os.OpenFile(fileName, os.O_APPEND, 0666)
} else {
f2, _ = os.Create(fileName)
}
defer f2.Close()
fmt.Println("正在下载音频:" + titles[k][1])
// _, _ = io.WriteString(f2, "https://res.wx.qq.com/voice/getvoice?mediaid="+v[1]+"\n")
// _, _ =f2.Write([]byte("https://res.wx.qq.com/voice/getvoice?mediaid="+v[1]+"\n"))
_, _ = f2.WriteString("https://res.wx.qq.com/voice/getvoice?mediaid=" + v[1] + "\n")
// _, _ = ioutil.WriteFile(fileName, []byte("https://res.wx.qq.com/voice/getvoice?mediaid="+v[1]+"\n"), 0666)
}
fmt.Print("下载完成")
}
输入话题地址https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MjM5NjAxOTU4MA==&action=getalbum&album_id=1777378132866465795&scene=173 就行,下载效果:
另外增加个功能,就是第2次下载会忽略已经下载过的音频:
由于python打包的exe在win7下运行不了,不知道golang打包的是否正常运行,有win7的小伙伴可以反馈下,谢谢。
exe地址: https://wwn.lanzouy.com/i88ck0cvdk9g
golang还挺方便的,之后打算把我之前python写的批量下载公众号文章内容音频视频再重写了,算熟悉下golang。
|