golang爬取豆瓣电影TOP250(下载图片)
source link: https://studygolang.com/articles/18738?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
打开豆瓣电影TOP250,打算爬取电影的四个信息,豆瓣排名,图片,评分,电影名。
所以先定义个结构体
type Movie struct { Num string Url string Star string Name string }
注意豆瓣电影的网址,是有规律的:
每一页 start
分别为0,25,50.....
所以在主函数里面加个循环:
func main(){ t1 := time.Now() for i := 0; i < 11; i++ { url := fmt.Sprintf("https://movie.douban.com/top250?start=%v&filter=", i*25) fmt.Printf("整在爬取第%v页",i+1) res := getResponse(url)//定义的获取html的函数 DownloadImg(res)// 下载图片的函数 } elapsed := time.Since(t1) fmt.Println("总共用时: ", elapsed) }
爬虫第一步,获取html网页进行解析,安装 goquery
gopm -g -v github.com/PuerkitoBio/goquery
func getResponse(url string) []Movie{ content,err:= goquery.NewDocument(url) if err != nil{ panic(err) } return ParseResponse(content)// } func ParseResponse(doc *goquery.Document) (pages []Movie) { doc.Find("div.item").Each(func(i int, s *goquery.Selection) { img,_ :=s.Find("img").Attr("src") num:=s.Find("em").Text() star:=s.Find("span.rating_num").Text() name,_:=s.Find("img").Attr("alt") pages = append(pages, Movie{ Num: num, Url: img, Star: star, Name: name, }) }) return pages }
这里把 ParseResponse
函数作为返回值,把处理后的 Movie
切片返回。处理网页用到 goquery
的Find匹配网页元素。
查看网页的元素代码,看到这几个需要获取的信息都在 <div class="item>
中,所以先循环获取 item
:
doc.Find("div.item").Each(func(i int, s *goquery.Selection)
打印出来大概就是这样的:
[.....{26 https://img3.doubanio.com/vie... 9.2 乱世佳人} {27 https://img3.doubanio.com/vie... 9.1 蝙蝠侠:黑暗骑士}....]
最后一步下载图片,把图片url和图片名称传给 GetImg
方法。
func GetImg(url string , name string) { res, _ := http.Get(url) file_name := imgpath + "\\" + name + ".jpg" //拼接图片路径 file, _ := os.Create(file_name) io.Copy(file, res.Body) }
网速比较慢,测了几次都是10s多一点。
完整代码 点这里
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK