package main
import (
"fmt"
"io"
"net/http"
"os"
"regexp"
"strconv"
)
//爬取指定url的页面,返回result
func HttpGet2(url string) (result string, err error) {
resp, err1 := http.Get(url)
if err1 != nil {
err = err1
return
}
defer resp.Body.Close()
buf := make([]byte, 4096)
//循环爬取整页数据
for {
n, err2 := resp.Body.Read(buf)
if n == 0 {
break
}
if err2 != nil && err2 != io.EOF {
err = err2
return
}
result += string(buf[:n])
}
return
}
func Save2file(idx int, filmName, filmScore, filmpeople [][]string) {
f, err := os.Create("第" + strconv.Itoa(idx) + "页.txt")
if err != nil {
fmt.Println("os.Create err:", err)
return
}
defer f.Close()
n := len(filmName) //得到条目数。
//先打印抬头 电影名称 评分 评分人数
f.WriteString("电影名称" + "\t\t\t" + "评分" + "\t\t" + "评分人数" + "\n")
for i := 0; i < n; i++ {
f.WriteString(filmName[i][1] + "\t\t\t" + filmScore[i][1] + "\t\t" + filmpeople[i][0] + "\n")
}
}
//爬取一个页面信息
func SpiderPage2(idx int) {
//获取url
url := "http://imdb.kxapps.com/default.aspx?page=" + strconv.Itoa(idx)
//url := "https://movie.douban.com/top250"
//封装httpget2爬取url对应页面
result, err := HttpGet2(url)
if err != nil {
fmt.Println("HttpGet2 err:", err)
return
}
//fmt.Println("result=", result)
//解析,编译正则表达式——电影名称
ret1 := regexp.MustCompile(` )
//提取需要信息
//电影名称
filmName := ret1.FindAllStringSubmatch(result, -1)
//评分
ret2 := regexp.MustCompile(``)
filmScore := ret2.FindAllStringSubmatch(result, -1)
//评分人数
ret3 := regexp.MustCompile(`>(.*?)人评分`)
filmpeople := ret3.FindAllStringSubmatch(result, -1)
//将提前的有用信息封装到文件中
Save2file(idx, filmName, filmScore, filmpeople)
}
func toWork(start, end int) {
fmt.Printf("正在爬取%d到%d页...\n", start, end)
for i := start; i <= end; i++ {
SpiderPage2(i)
}
}
func main() {
//指定爬取起始,终止页
var start, end int
fmt.Print("请输入爬取的起始页(>=1):")
fmt.Scan(&start)
fmt.Print("请输入爬取的终止页(>=strart):")
fmt.Scan(&end)
toWork(start, end)
}
二、效果展示
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)