-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoudao.go
51 lines (41 loc) · 968 Bytes
/
youdao.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
package main
import (
"fmt"
"github.com/antchfx/htmlquery"
"io/ioutil"
"net/http"
"os"
"strings"
)
const URL = "https://dict.youdao.com/w/eng/%s/#keyfrom=dict2.index"
func translate(words string) string {
words = strings.ReplaceAll(words, "/", "/")
url := fmt.Sprintf(URL, words)
response, err := http.Get(url)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
defer response.Body.Close()
content, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
doc, err := htmlquery.Parse(strings.NewReader(string(content)))
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
result := htmlquery.FindOne(doc, "//div[@id='results-contents']")
content = []byte(htmlquery.OutputHTML(result, true))
return string(content)
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide a word to translate.")
os.Exit(1)
}
result := translate(os.Args[1])
fmt.Println(result)
}