GolangNote

Golang笔记

通过 Golang http get 获取 google 搜索建议/自动完成

Permalink

在 Chrome 打开 Google 搜索,在搜索输入框输入关键字时会有自动完成的下拉框,可以通过简单的 http 请求得到相关搜索建议。

获取 google 搜索建议/自动完成

实现代码很简单:

Go: 搜索建议
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
}

怎么了?中文乱码!!

伸手党

Go:
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)

备用接口:

plaintext: 备用建议接口
1
https://suggestqueries.google.com/complete/search

本文网址: https://golangnote.com/topic/293.html 转摘请注明来源

Related articles

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Write a Comment to "通过 Golang http get 获取 google 搜索建议/自动完成"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms