main.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/gocolly/colly"
  6. "github.com/tidwall/gjson"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "sync"
  15. "time"
  16. )
  17. var downloadDestFolder = "D:\\music"
  18. var w sync.WaitGroup
  19. func main() {
  20. url := flag.String("url", "http://yinyue.kuwo.cn/yy/cinfo_73195.htm", "酷我歌单地址")
  21. //bangdan:=flag.Int("bang",1,"榜单ID:16-酷我热歌榜;17-酷我新歌榜")
  22. flag.Parse()
  23. c := colly.NewCollector()
  24. c.OnResponse(func(response *colly.Response) {
  25. reg := regexp.MustCompile(`jsonm = (.*);`)
  26. pat := reg.FindSubmatch(response.Body)
  27. jsonStr := string(pat[1])
  28. ParseJson(jsonStr)
  29. })
  30. c.Visit(*url)
  31. }
  32. func ParseJson(content string) {
  33. musiclist := gjson.Get(content, "musiclist")
  34. //c := colly.NewCollector()
  35. if musiclist.Exists() {
  36. re := musiclist.Array()
  37. for _, v := range re {
  38. musicrid := v.Get("musicrid").String()
  39. name := v.Get("name").String()
  40. artist := v.Get("artist").String()
  41. client := http.Client{Timeout: 900 * time.Second}
  42. url := fmt.Sprintf("http://antiserver.kuwo.cn/anti.s?format=mp3&type=convert_url&rid=MUSI_%s&response=url", musicrid)
  43. resp, _ := client.Get(url)
  44. body, _ := ioutil.ReadAll(resp.Body)
  45. resp.Body.Close()
  46. w.Add(1)
  47. go download(string(body), fmt.Sprintf("%s.mp3", name))
  48. time.Sleep(time.Duration(200) * time.Millisecond)
  49. }
  50. }
  51. w.Wait()
  52. }
  53. func download(url string, filename string) {
  54. defer w.Done()
  55. nt := time.Now().Format("2006-01-02 15:04:05")
  56. fmt.Printf("[%s]To download %s\n", nt, filename)
  57. _ = os.MkdirAll(downloadDestFolder, 0777)
  58. fpath := downloadDestFolder + string(filepath.Separator) + filename
  59. newFile, err := os.Create(fpath)
  60. if err != nil {
  61. fmt.Println(err.Error())
  62. }
  63. defer newFile.Close()
  64. client := http.Client{Timeout: 900 * time.Second}
  65. resp, err := client.Get(url)
  66. defer resp.Body.Close()
  67. _, err = io.Copy(newFile, resp.Body)
  68. if err != nil {
  69. fmt.Println(err.Error())
  70. }
  71. log.Println("Saved:", filename)
  72. }