Go语言 如何在chromedp上截图,运行失败?

yzxexxkh  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(144)

我想有一个浏览器的屏幕截图是如何看起来像一个错误(上下文截止日期超过)发生时(最好是在无头和头部模式)。
我将chromedp.Screenshot(...)添加到chromedp.Run流程中,当运行通过时,它会正确地截取屏幕截图,但是当它失败时,错误会在屏幕截图步骤之前发生,并导致浏览器关闭,因此无法捕获屏幕截图。谢谢!

uajslkp6

uajslkp61#

解决方法是利用屏幕播放功能,并在出现问题时保存最后一帧(或几帧):

  1. package main
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "os"
  7. "github.com/chromedp/cdproto/page"
  8. "github.com/chromedp/chromedp"
  9. )
  10. func main() {
  11. ctx, cancel := chromedp.NewContext(context.Background())
  12. defer cancel()
  13. var screenshot string
  14. chromedp.ListenTarget(ctx, func(ev interface{}) {
  15. if ev, ok := ev.(*page.EventScreencastFrame); ok {
  16. // Only keep the last frame.
  17. // You can modify the code to keep several frames or all the frames.
  18. screenshot = ev.Data
  19. go func() {
  20. _ = chromedp.Run(ctx, page.ScreencastFrameAck(ev.SessionID))
  21. }()
  22. }
  23. })
  24. if err := chromedp.Run(ctx,
  25. page.StartScreencast(),
  26. // Put your actions here.
  27. page.StopScreencast(),
  28. ); err != nil {
  29. if screenshot != "" {
  30. buf, err := base64.StdEncoding.DecodeString(screenshot)
  31. if err != nil {
  32. fmt.Printf("failed to decode the screenshot data: %v\n", err)
  33. } else {
  34. _ = os.WriteFile("screenshot.png", buf, 0o644)
  35. }
  36. }
  37. panic(err)
  38. }
  39. }

字符集

展开查看全部

相关问题