selenium相信大家都不陌生,从最开始的selenium core到现在的RC,利用selenium能干的事情也越来越多。也用go+selenium写了一些小工具,测试了一下各大网站关注好友的接口~
这里先介绍下用到的库:
https://github.com/tebeka/selenium
接下来可以试试先运行提供的example:
作者提供的example是在linux下运行,如果要在windows下需要做一些调整:
1.webdriver,selenium路径:
2. 屏蔽FrameBuffer
分享一下,自己写的demo,打开百度,输入selenium,点击搜索:
package main
import (
"fmt"
"github.com/tebeka/selenium"
"io/ioutil"
"os"
"os/signal"
"syscall"
)
var (
sigs chan os.Signal
)
func init() {
sigs = make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
}
func main() {
const (
// These paths will be different on your system.
seleniumPath = "./vender/selenium-server-standalone-3.8.1.jar"
geckoDriverPath = "./vender/geckodriver.exe"
port = 8080
)
opts := []selenium.ServiceOption{
selenium.GeckoDriver(geckoDriverPath), // Specify the path to GeckoDriver in order to use Firefox.
selenium.Output(ioutil.Discard), // Output debug information to STDERR.
}
selenium.SetDebug(false)
service, err := selenium.NewSeleniumService(seleniumPath, port, opts...)
if err != nil {
panic(err) // panic is used only as an example and is not otherwise recommended.
}
defer service.Stop()
// Connect to the WebDriver instance running locally.
caps := selenium.Capabilities{"browserName": "firefox"}
wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
if err != nil {
panic(err)
}
defer wd.Quit()
// Navigate to the simple playground interface.
if err := wd.Get("https://www.baidu.com/"); err != nil {
panic(err)
}
wd.SetImplicitWaitTimeout(4)
input,err:=wd.FindElement(selenium.ByCSSSelector,"#kw")
if err!=nil{
panic(err)
}
input.SendKeys("selenium")
search,err:=wd.FindElement(selenium.ByCSSSelector,"#su")
if err!=nil{
panic(err)
}
search.Click()
<-sigs
}
需要用到的jar,exe文件下载地址:
Selenium: https://selenium-release.storage.googleapis.com/3.8/selenium-server-standalone-3.8.1.jar
Webdriver: https://github.com/mozilla/geckodriver/releases/download/v0.23.0/geckodriver-v0.23.0-win64.zip