Web自动化Demo-Go+Selenium

时间:2024-10-14 06:58:30

1.新建工程

使用GoLand新建工程如下:

打开终端输入如下命令安装Selenium

go get -u github.com/tebeka/selenium

2.编写代码

package main

import (
	"fmt"
	"github.com/tebeka/selenium"
	"log"
	"time"
)

const (
	chromeDriverPath = "/opt/homebrew/bin/chromedriver"
	port             = 4444
)

func main() {
	var opts []selenium.ServiceOption
	service, err := selenium.NewChromeDriverService(chromeDriverPath, port, opts...)
	if err != nil {
		log.Fatalf("Error starting the ChromeDriver server: %v", err)
	}
	defer func(service *selenium.Service) {
		err := service.Stop()
		if err != nil {
			log.Fatalf("Error to stop: %v", err)
		}
	}(service)
	caps := selenium.Capabilities{
		"browserName": "chrome",
	}
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
	if err != nil {
		log.Fatalf("Error creating new WebDriver instance: %v", err)
	}
	defer func(wd selenium.WebDriver) {
		err := wd.Quit()
		if err != nil {
			log.Fatalf("Error to quit: %v", err)
		}
	}(wd)
	err = wd.Get("https://www.baidu.com")
	if err != nil {
		log.Fatalf("Failed to load page: %s\n", err)
	}
	time.Sleep(3 * time.Second)
	searchBox, err := wd.FindElement(selenium.ByID, "kw")
	if err != nil {
		log.Fatalf("Failed to find search input box: %s\n", err)
	}
	err = searchBox.SendKeys("Hello")
	if err != nil {
		log.Fatalf("Failed to send keys to search input box: %s\n", err)
	}
	searchButton, err := wd.FindElement(selenium.ByID, "su")
	if err != nil {
		log.Fatalf("Failed to find search button: %s\n", err)
	}
	err = searchButton.Click()
	time.Sleep(3 * time.Second)
}

然后执行main函数即可