Web自动化Demo-Go+Selenium

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函数即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值