- package main
- import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "net/http"
- "os"
- "runtime"
- "strings"
- )
- func getImg(url string, c chan int) (n int64, err error) {
- path := strings.Split(url, "/")
- var name string
- if len(path) > 1 {
- name = path[len(path)-1]
- }
- fmt.Println(name)
- out, err := os.Create(name)
- defer out.Close()
- resp, err := http.Get(url)
- defer resp.Body.Close()
- pix, err := ioutil.ReadAll(resp.Body)
- n, err = io.Copy(out, bytes.NewReader(pix))
- c <- 1
- return
- }
- func main() {
- runtime.GOMAXPROCS(4)
- resp, err := http.Get("http://www.jj20.com/bz/zrfg/fghj/4815.html")
- if err != nil {
- return
- }
- body, err := ioutil.ReadAll(resp.Body)
- resp.Body.Close()
- html := string(body)
- table := strings.Split(html, "<table width=\\"100%\\" border=\\"0\\" cellspacing=\\"0\\" cellpadding=\\"0\\" align=\\"center\\">")
- ul := ""
- if len(table) > 1 {
- ul = table[1]
- }
- if ul != "" {
- lis := strings.Split(ul, "</ul>")
- if len(lis) >= 1 {
- hrefs := strings.Split(lis[0], "<li>")
- var c = make(chan int)
- for _, href := range hrefs {
- imgSrc := strings.Split(href, "src=\\"")
- if len(imgSrc) > 1 {
- src := strings.Split(imgSrc[1], "\\"")[0]
- go getImg(src, c)
- }
- }
- for i := 1; i < len(hrefs); i++ {
- <-c
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/030420149227.html
来源: http://www.codesnippet.cn/detail/030420149227.html