在 Chrome 打开 Google 搜索,在搜索输入框输入关键字时会有自动完成的下拉框,可以通过简单的 http 请求得到相关搜索建议。
实现代码很简单:
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
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
)
const BaseURL = "https://www.google.com/complete/search?output=search&client=chrome&hl=zh-CN&q="
func main() {
query := "apples and oranges"
suggestions, err := Get(query)
if err != nil {
panic(err)
}
for _, suggestion := range suggestions {
fmt.Println(suggestion)
}
}
// Suggestions is a slice of strings that is returned by Suggest
type Suggestions = []string
// Get queries google's unofficial suggestion API for Suggestions.
func Get(str string) (Suggestions, error) {
query := url.QueryEscape(str)
resp, err := http.Get(BaseURL + query)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw := []json.RawMessage{}
err = json.NewDecoder(resp.Body).Decode(&raw)
if err != nil {
return nil, err
}
if len(raw) < 2 {
return nil, errors.New("no suggestion data found")
}
sgs := Suggestions{}
err = json.Unmarshal(raw[1], &sgs)
if err != nil {
return nil, err
}
return sgs, nil
}
怎么了?中文乱码!!
伸手党
1
2
3
4
5
6
7
client := &http.Client{}
req, err := http.NewRequest("GET", BaseURL+query, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36")
resp, err := client.Do(req)
备用接口:
1
https://suggestqueries.google.com/complete/search
本文网址: https://golangnote.com/topic/293.html 转摘请注明来源