Go 爬蟲:如何獲取 js 檔案中固定的內容?
簡介

我想爬豆瓣電影的分類,網址是 https://movie.douban.com/tag/
。發現呼叫介面,返回的資料並沒有我所需要的內容。
我自己看了一下介面呼叫,發現這些分類竟然是在 app.js
的二維陣列固定寫死的。

妹的,這就尷尬了,我豈不是要等待瀏覽器渲染完之後再匹配我想要的資料?
查查Go有沒有庫可以模擬瀏覽器的操作。發現了一個 chromedp
。於是查找了一些資料,學習了一下。
github地址
倉庫地址: ofollow,noindex">https://github.com/chromedp/chromedp
例子地址: https://github.com/chromedp/examples
參考的文件:
https://deepzz.com/post/golang-context-package-notes.html
https://www.cnblogs.com/apocelipes/p/9264673.html
https://codeday.me/news/20170529/20419.html程式碼
獲取豆瓣網站的電影分類。
// Command text is a chromedp example demonstrating how to extract text from a // specific element. package main import ( "context" "fmt" "log" "os" "regexp" "time" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/runner" ) func text(res *string) chromedp.Tasks { return chromedp.Tasks{ // 訪問頁面 chromedp.Navigate(`https://movie.douban.com/tag/`), // 等待列表渲染 chromedp.Sleep(5 * time.Second), // 獲取獲取服務列表HTML chromedp.OuterHTML("#content", res, chromedp.ByID), } } func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // 建立 chrome 例項 cdp, err := chromedp.New(ctx, chromedp.WithLog(log.Printf)) if err != nil { log.Fatal(err) } var res string //執行呼叫 err = cdp.Run(ctx, text(&res)) if err != nil { log.Fatal(err) } // 呼叫 Shutdown err = cdp.Shutdown(ctx) if err != nil { log.Fatal(err) } // 等待 chrome 結束 err = cdp.Wait() if err != nil { log.Fatal(err) } // 正則匹配所要的內容 pattern := `class="tag">(.*?)</span>` rp2 := regexp.MustCompile(pattern) data := rp2.FindAllStringSubmatch(res, -1) // 建立一個 txt 檔案,寫入獲取的內容 f, err := os.Create("fenlei.txt") if err != nil { log.Fatalln(err) } // 關閉 f defer f.Close() // 遍歷切片,獲取需要的內容,並寫入 txt 檔案 for i := 0; i < len(data); i++ { fmt.Println(data[i][1]) f.WriteString(data[i][1] + "\n") } }