使用 chromedp 實(shí)現(xiàn)網(wǎng)頁(yè)快照
github地址為:github.com/chromedp/chromedp
實(shí)例代碼
package main
import (
????"context"
????"io/ioutil"
????"log"
????"math"
????"github.com/chromedp/cdproto/emulation"
????"github.com/chromedp/cdproto/page"
????"github.com/chromedp/chromedp"
????"time"
)
func main() {
????ctx, cancel := chromedp.NewContext(context.Background())
????defer cancel()
????var buf []byte
? ????if err := chromedp.Run(ctx, fullScreenshot("https://www.baidu.com", 90, &buf)); err != nil {
????????log.Fatal(err)
????}
????if err := ioutil.WriteFile("fullScreenshot.png", buf, 0644); err != nil {
????????log.Fatal(err)
????}
}
func fullScreenshot(urlstrstring, qualityint64, res *[]byte) chromedp.Tasks {
????return chromedp.Tasks{
????????chromedp.Navigate(urlstr),
? ? ? ? chromedp.ActionFunc(func(ctx context.Context)error {
????????????// get layout metrics
? ? ? ????? _, _, contentSize, err := page.GetLayoutMetrics().Do(ctx)
????????????if err != nil {
????????????????return err
????????????}
????????????width, height :=int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height))
????????????// force viewport emulation
? ? ? ? err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
????????????WithScreenOrientation(&emulation.ScreenOrientation{
????????????Type:? emulation.OrientationTypePortraitPrimary,
? ? ? ? ? ? Angle:0,
? ? ? ? }).Do(ctx)
????????if err != nil {
????????????return err
????????}
????????chromedp.Sleep(2 * time.Second)
????????// capture screenshot
? ? ? ? *res, err = page.CaptureScreenshot().
????????????WithQuality(quality).
????????????WithClip(&page.Viewport{
????????????X:? ? ? contentSize.X,
? ? ? ? ? ? Y:? ? ? contentSize.Y,
? ? ? ? ? ? Width:? contentSize.Width,
? ? ? ? ? ? Height: contentSize.Height,
? ? ? ? ? ? Scale:1,
? ? ? ? }).Do(ctx)
????????if err != nil {
????????????return err
????????}
????????return nil????
????}),
? }
}
網(wǎng)頁(yè)快照