package main
import (
"fmt"
"net/http"
"os"
"strconv"
)
func HttpGet(url string) (result string, err error) {
resp, err1 := http.Get(url)
if err1 != nil {
err = err1
return
}
defer resp.Body.Close()
buf := make([]byte, 1024*4)
for {
n, err := resp.Body.Read(buf)
if n == 0 { //读取结束,或者,出问题
fmt.Println("resp.Body.Read err = ", err)
break
}
result += string(buf[:n])
}
return
}
func SpiderPape(i int, page chan<- int) {
url := "http://tieba.baidu.com/f?kw=keep&ie=utf-8&pn=" + strconv.Itoa((i-1)*50)
fmt.Println("url == ", url)
result, err := HttpGet(url)
if err != nil {
fmt.Println("HttpGrt err = ", err)
return
}
//把内容写入到文件
fileName := strconv.Itoa(i) + ".html"
f, err1 := os.Create(fileName)
defer f.Close()
if err1 != nil {
fmt.Println("OsCreate err1 = ", err1)
return
}
f.WriteString(result)
page <- i
}
func DoWork(start, end int) {
fmt.Printf("正在爬取 %d - %d\n", start, end)
//明确目标
//http://tieba.baidu.com/f?kw=keep&ie=utf-8&pn=0
page := make(chan int)
for i := start; i <= end; i++ {
go SpiderPape(i, page)
}
for i := start; i <= end; i++ {
fmt.Printf("爬取第 %d 个页面完成!", <-page)
}
}
func main() {
var start, end int
fmt.Printf("输入起始页(>= 1):")
fmt.Scan(&start)
fmt.Printf("输入终止页(>= 起始页):")
fmt.Scan(&end)
DoWork(start, end)
}