Go 使用 selenium 截图
Go 使用 selenium 截图 package main import ( "fmt" log "github.com/sirupsen/logrus" "github.com/tebeka/selenium" "io/ioutil" ) const ( chromeDriverPath = "/usr/local/bin/chromedriver" port = 9515 ) func main() { var opts []selenium.ServiceOption selenium.SetDebug(false) service, err := selenium.NewChromeDriverService(chromeDriverPath, port, opts...) if err != nil { panic(err) // panic is used only as an example and is not otherwise recommended. } defer service.Stop() caps := selenium.Capabilities{"browserName": "chrome"} // 整页截屏 // 获取到网页的宽高,然后把浏览器的窗口设置成这么大,然后再截图就好了!需要注意的是只有 headless 模式可以任意设置窗口大小,否则最大高度不能超过你的显示器分辨率 // chromeCaps := chrome.Capabilities{ // Path: "", // Args: []string{ // "--headless", // }, // } // caps.AddChrome(chromeCaps) wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port)) if err != nil { panic(err) } defer wd.Quit() // 在 selenium 中使用ExecuteScript就可以执行 JavaScript 代码,需要注意返回值是 interface,所以要类型断言成 float,然后再转成 int // height, _ := wd.ExecuteScript("return document.body.parentNode.scrollHeight", nil) // var realHeight = int(height.(float64)) // 然后我们需要设置窗口大小 // wd.ResizeWindow("", 1920, realHeight) if err := wd.Get("https://github.com/tgbot-collection/archiver"); err != nil { panic(err) } screenshot, err := wd.Screenshot() if err != nil { log.Errorln(err) } ioutil.WriteFile("screenshot.png", screenshot, 0644) } 整页截屏 获取到网页的宽高,然后把浏览器的窗口设置成这么大,然后再截图就好了!需要注意的是只有 headless 模式可以任意设置窗口大小,否则最大高度不能超过你的显示器分辨率