golang是近幾年發展很是迅猛的一款服務器端的語言,其生態也日益豐富。對於使用golang實現網頁截圖這個需求,筆者在通過一番調研以後發現你們有推薦Selenium方案,可是這一方案問題較多:golang
還有推薦headless chrome方案的,可是這一方案也須要自行在服務器端安裝一款瀏覽器,對服務器的壓力比較大,併發性能也很差,因此最後筆者直接選用了一款第三方API的截圖服務。chrome
該服務有以下特色:api
使用方式也很簡單,咱們打開它的首頁 https://www.screenshotmaster.com/ 註冊一個帳號,而後你會在用戶中心獲取到一個惟一的Token,保存好這個Token 不要泄漏!瀏覽器
下面來看看它支持的參數:服務器
您能夠前往API文檔頁面查看更多的參數。併發
使用golang調用截屏大師的接口獲取截圖:less
package main import ( "fmt" "io" "io/ioutil" "net/http" url2 "net/url" "os" ) func main() { // 參數 token := "YOUR_API_TOKEN" url := url2.QueryEscape("https://www.baidu.com") width := 1280 height := 800 full_page := 1 // 構造URL query := "https://www.screenshotmaster.com/api/v1/screenshot" query += fmt.Sprintf("?token=%s&url=%s&width=%d&height=%d&full_page=%s", token, url, width, height, full_page) // 調用API resp, err := http.Get(query) if err != nil { panic(err) } defer resp.Body.Close() // 檢查是否調用成功 if resp.StatusCode != 200 { errorBody, _ := ioutil.ReadAll(resp.Body) panic(fmt.Errorf("error while calling api %s", errorBody)) } // 保存截圖 file, err := os.Create("./screenshot.png") if err != nil { panic(err) } defer file.Close() _, err = io.Copy(file, resp.Body) if err != nil { panic(err) } }