golang爬取豆瓣電影TOP250(下載圖片)

打開豆瓣電影TOP250,打算爬取電影的四個信息,豆瓣排名,圖片,評分,電影名。html

clipboard.png
因此先定義個結構體git

type Movie struct {
    Num     string
    Url      string
    Star     string
    Name     string

}

注意豆瓣電影的網址,是有規律的:github

clipboard.png

每一頁start分別爲0,25,50.....
因此在主函數裏面加個循環:golang

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網頁進行解析,安裝goqueryapp

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匹配網頁元素。函數

clipboard.png

查看網頁的元素代碼,看到這幾個須要獲取的信息都在<div class="item>中,因此先循環獲取item:post

doc.Find("div.item").Each(func(i int, s *goquery.Selection)

打印出來大概就是這樣的:url

[.....{26 https://img3.doubanio.com/vie... 9.2 亂世佳人} {27 https://img3.doubanio.com/vie... 9.1 蝙蝠俠:黑暗騎士}....]

最後一步下載圖片,把圖片url和圖片名稱傳給GetImg方法。spa

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)
}

clipboard.png
網速比較慢,測了幾回都是10s多一點。3d

clipboard.png

完整代碼點這裏


參考文檔:
golang goquery selector(選擇器) 示例大全
Golang爬蟲 爬取豆瓣電影Top250

相關文章
相關標籤/搜索