2024-05-17 14:26:28 +02:00
|
|
|
|
// text-google.go
|
2024-04-15 08:35:17 +02:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"log"
|
|
|
|
|
"net/http"
|
|
|
|
|
"net/url"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/PuerkitoBio/goquery"
|
|
|
|
|
)
|
|
|
|
|
|
2024-05-17 14:26:28 +02:00
|
|
|
|
func PerformGoogleTextSearch(query, safe, lang string) ([]TextSearchResult, error) {
|
2024-04-15 08:35:17 +02:00
|
|
|
|
var results []TextSearchResult
|
|
|
|
|
|
|
|
|
|
client := &http.Client{}
|
|
|
|
|
safeParam := "&safe=off"
|
|
|
|
|
if safe == "active" {
|
|
|
|
|
safeParam = "&safe=active"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
langParam := ""
|
|
|
|
|
if lang != "" {
|
|
|
|
|
langParam = "&lr=" + lang
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
searchURL := "https://www.google.com/search?q=" + url.QueryEscape(query) + safeParam + langParam
|
|
|
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", searchURL, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatalf("Failed to create request: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")
|
|
|
|
|
|
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
doc.Find(".yuRUbf").Each(func(i int, s *goquery.Selection) {
|
|
|
|
|
link := s.Find("a")
|
|
|
|
|
href, _ := link.Attr("href")
|
|
|
|
|
header := link.Find("h3").Text()
|
|
|
|
|
header = strings.TrimSpace(strings.TrimSuffix(header, "›"))
|
|
|
|
|
|
|
|
|
|
descSelection := doc.Find(".VwiC3b").Eq(i)
|
|
|
|
|
description := ""
|
|
|
|
|
if descSelection.Length() > 0 {
|
|
|
|
|
description = descSelection.Text()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
results = append(results, TextSearchResult{
|
|
|
|
|
URL: href,
|
|
|
|
|
Header: header,
|
|
|
|
|
Description: description,
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return results, nil
|
|
|
|
|
}
|