体验一下 Go Selenium Go主题月

写爬虫的朋友一定了解过浏览器自动化,比如 Selenium 或者 Puppeteer,这其中我用的比较多的是 Selenium,Selenium 是一个用于 Web 应用程序测试的工具。Selenium 测试直接运行在浏览器中,就像真正的用户在操作一样。所以我们会使用 Selenium 进行模仿用户进行操作浏览器爬取数据。

之前使用的开发语言是 Python,今天我们来试试 Go selenium 吧。

安装

目前我正在使用的一个依赖库是 github.com/tebeka/sele…,功能较完整且处于维护中。

1
bash复制代码go get -t -d github.com/tebeka/selenium

另外,我们需要对应不同类型的浏览器进行安装 WebDriver,Google Chrome 需要安装 ChromeDriver,Firefox 则需要安装 geckodriver

案例

这里我们使用的 Google Chrome,我们首先要指定 ChromeDriver 的位置并启动一个 WebDriver server,然后就可以开始操作浏览器了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
go复制代码package main

import (
"fmt"
"os"
"strings"
"time"

"github.com/tebeka/selenium"
)

const (
chromeDriverPath = "/path/to/chromedriver"
port = 8080
)

func main() {
// Start a WebDriver server instance
opts := []selenium.ServiceOption{
selenium.Output(os.Stderr), // Output debug information to STDERR.
}
selenium.SetDebug(true)
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()

// Connect to the WebDriver instance running locally.
caps := selenium.Capabilities{"browserName": "chrome"}
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("http://play.golang.org/?simple=1"); err != nil {
panic(err)
}

// Get a reference to the text box containing code.
elem, err := wd.FindElement(selenium.ByCSSSelector, "#code")
if err != nil {
panic(err)
}
// Remove the boilerplate code already in the text box.
if err := elem.Clear(); err != nil {
panic(err)
}

// Enter some new code in text box.
err = elem.SendKeys(`
package main
import "fmt"
func main() {
fmt.Println("Hello WebDriver!")
}
`)
if err != nil {
panic(err)
}

// Click the run button.
btn, err := wd.FindElement(selenium.ByCSSSelector, "#run")
if err != nil {
panic(err)
}
if err := btn.Click(); err != nil {
panic(err)
}

// Wait for the program to finish running and get the output.
outputDiv, err := wd.FindElement(selenium.ByCSSSelector, "#output")
if err != nil {
panic(err)
}

var output string
for {
output, err = outputDiv.Text()
if err != nil {
panic(err)
}
if output != "Waiting for remote server..." {
break
}
time.Sleep(time.Millisecond * 100)
}

fmt.Printf("%s", strings.Replace(output, "\n\n", "\n", -1))

// Example Output:
// Hello WebDriver!
//
// Program exited.
}

总结

使用起来并不是很复杂,但是感觉 Go Selenium 并不是很流行,github.com/tebeka/sele… 在 GitHub 上的 Star 数只有 1k+。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%