Hızlı Başlangıç: Bing Web Araması REST API'sini ve Go'yı kullanarak web'de arama yapın
Uyarı
30 Ekim 2020'de Bing Arama API'leri Azure yapay zeka hizmetlerinden Bing Arama Hizmetlerine taşındı. Bu belgeler yalnızca başvuru için sağlanır. Güncelleştirilmiş belgeler için Bing arama API'sinin belgelerine bakın. Bing araması için yeni Azure kaynakları oluşturma yönergeleri için bkz. Azure Market aracılığıyla Bing Arama kaynağı oluşturma.
Bing Web Araması API'sine ilk çağrınızı yapmak için bu hızlı başlangıcı kullanın. Bu Go uygulaması API'ye bir arama isteği gönderir ve JSON yanıtını gösterir. Bu uygulama Go dilinde yazılmış olsa da, API çoğu programlama diliyle uyumlu bir RESTful Web hizmetidir.
Bu hızlı başlangıçtaki kod örnekleri yalnızca çekirdek kitaplıklar gerektirir; dış bağımlılık yoktur.
Önkoşullar
Bu hızlı başlangıcı çalıştırmak için aşağıdakilere ihtiyacınız olacaktır:
- Go ikilileri
- Abonelik anahtarı
Azure kaynağı oluşturma
Aşağıdaki Azure kaynaklarından birini oluşturarak Bing Web Araması API'sini kullanmaya başlayın:
- Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
- Hizmeti denemek için ücretsiz fiyatlandırma katmanını kullanın ve daha sonra üretim için ücretli bir katmana yükseltin.
- Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
- Birden çok Azure AI hizmeti genelinde uygulamalarınız için aynı anahtarı ve uç noktayı kullanın.
Proje oluşturma ve çekirdek kitaplıkları içeri aktarma
Sık kullandığınız IDE'de veya düzenleyicide yeni bir Go projesi oluşturun. Ardından istekleri içeri aktarın net/http
, ioutil
yanıtı time
okuyun, encoding/json
JSON'u işleyin ve fmt
çıktıyı yazdırın.
package main
import (
"fmt"
"net/http"
"io/ioutil"
"time"
"encoding/json"
)
Arama sonuçlarını biçimlendirmek için yapı oluşturma
BingAnswer
yapısı, yanıtta sağlanan verileri biçimlendirir.
// This struct formats the answers provided by the Bing Web Search API.
type BingAnswer struct {
Type string `json:"_type"`
QueryContext struct {
OriginalQuery string `json:"originalQuery"`
} `json:"queryContext"`
WebPages struct {
WebSearchURL string `json:"webSearchUrl"`
TotalEstimatedMatches int `json:"totalEstimatedMatches"`
Value []struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
IsFamilyFriendly bool `json:"isFamilyFriendly"`
DisplayURL string `json:"displayUrl"`
Snippet string `json:"snippet"`
DateLastCrawled time.Time `json:"dateLastCrawled"`
SearchTags []struct {
Name string `json:"name"`
Content string `json:"content"`
} `json:"searchTags,omitempty"`
About []struct {
Name string `json:"name"`
} `json:"about,omitempty"`
} `json:"value"`
} `json:"webPages"`
RelatedSearches struct {
ID string `json:"id"`
Value []struct {
Text string `json:"text"`
DisplayText string `json:"displayText"`
WebSearchURL string `json:"webSearchUrl"`
} `json:"value"`
} `json:"relatedSearches"`
RankingResponse struct {
Mainline struct {
Items []struct {
AnswerType string `json:"answerType"`
ResultIndex int `json:"resultIndex"`
Value struct {
ID string `json:"id"`
} `json:"value"`
} `json:"items"`
} `json:"mainline"`
Sidebar struct {
Items []struct {
AnswerType string `json:"answerType"`
Value struct {
ID string `json:"id"`
} `json:"value"`
} `json:"items"`
} `json:"sidebar"`
} `json:"rankingResponse"`
}
Ana işlevi ve değişkenleri tanımlama
Bu kod main işlevini bildirir ve gerekli değişkenleri ayarlar:
Değeri için
endpoint
aşağıdaki kodda genel uç noktayı veya kaynağınızın Azure portal görüntülenen özel alt etki alanı uç noktasını kullanabilirsiniz.Uç noktasının geçerli olduğunu doğrulayın ve
token
değerini Azure hesabınızdan geçerli bir abonelik anahtarı ile değiştirin.İsteğe bağlı olarak, değerini değiştirerek arama sorgusunu özelleştirin
searchTerm
.
// Declare the main function. This is required for all Go programs.
func main() {
// Verify the endpoint URI and replace the token string with a valid subscription key.
const endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/search"
token := "YOUR-ACCESS-KEY"
searchTerm := "Microsoft Cognitive Services"
// The remaining code in this quickstart goes in the main function.
}
İstek oluşturma
Bu kod HTTP isteğini tanımlar, üst bilgiyi ve yükü ekler ve istemciyi başlatır.
// Declare a new GET request.
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
panic(err)
}
// Add the payload to the request.
param := req.URL.Query()
param.Add("q", searchTerm)
req.URL.RawQuery = param.Encode()
// Insert the request header.
req.Header.Add("Ocp-Apim-Subscription-Key", token)
// Instantiate a client.
client := new(http.Client)
İstekte bulunma
Bing Web Araması API'sini çağırmak ve yanıt döndürüldükten sonra bağlantıyı kapatmak için bu kodu kullanın.
// Send the request to Bing.
resp, err := client.Do(req)
if err != nil {
panic(err)
}
// Close the connection.
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
Yanıtı işleme
Yanıtı biçimlendirmek ve arama sonuçlarını yazdırmak için daha önce oluşturduğumuz yapıyı kullanın.
// Create a new answer.
ans := new(BingAnswer)
err = json.Unmarshal(body, &ans)
if err != nil {
fmt.Println(err)
}
// Iterate over search results and print the result name and URL.
for _, result := range ans.WebPages.Value {
fmt.Println(result.Name, "||", result.URL)
}
Hepsini bir araya getirin
Son adım kodunuzu doğrulamak ve çalıştırmaktır. Kodunuzu bizimkiyle karşılaştırmak isterseniz, tam program aşağıdadır:
package main
import (
"fmt"
"net/http"
"io/ioutil"
"time"
"encoding/json"
)
// The is the struct for the data returned by Bing.
type BingAnswer struct {
Type string `json:"_type"`
QueryContext struct {
OriginalQuery string `json:"originalQuery"`
} `json:"queryContext"`
WebPages struct {
WebSearchURL string `json:"webSearchUrl"`
TotalEstimatedMatches int `json:"totalEstimatedMatches"`
Value []struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
IsFamilyFriendly bool `json:"isFamilyFriendly"`
DisplayURL string `json:"displayUrl"`
Snippet string `json:"snippet"`
DateLastCrawled time.Time `json:"dateLastCrawled"`
SearchTags []struct {
Name string `json:"name"`
Content string `json:"content"`
} `json:"searchTags,omitempty"`
About []struct {
Name string `json:"name"`
} `json:"about,omitempty"`
} `json:"value"`
} `json:"webPages"`
RelatedSearches struct {
ID string `json:"id"`
Value []struct {
Text string `json:"text"`
DisplayText string `json:"displayText"`
WebSearchURL string `json:"webSearchUrl"`
} `json:"value"`
} `json:"relatedSearches"`
RankingResponse struct {
Mainline struct {
Items []struct {
AnswerType string `json:"answerType"`
ResultIndex int `json:"resultIndex"`
Value struct {
ID string `json:"id"`
} `json:"value"`
} `json:"items"`
} `json:"mainline"`
Sidebar struct {
Items []struct {
AnswerType string `json:"answerType"`
Value struct {
ID string `json:"id"`
} `json:"value"`
} `json:"items"`
} `json:"sidebar"`
} `json:"rankingResponse"`
}
// Verify the endpoint URI and replace the token string with a valid subscription key.
func main() {
const endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/search"
token := "YOUR-ACCESS-KEY"
searchTerm := "Microsoft Cognitive Services"
// Declare a new GET request.
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
panic(err)
}
// Add the payload to the request.
param := req.URL.Query()
param.Add("q", searchTerm)
req.URL.RawQuery = param.Encode()
// Insert the request header.
req.Header.Add("Ocp-Apim-Subscription-Key", token)
// Create a new client.
client := new(http.Client)
// Send the request to Bing.
resp, err := client.Do(req)
if err != nil {
panic(err)
}
// Close the response.
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
// Create a new answer.
ans := new(BingAnswer)
err = json.Unmarshal(body, &ans)
if err != nil {
fmt.Println(err)
}
// Iterate over search results and print the result name and URL.
for _, result := range ans.WebPages.Value {
fmt.Println(result.Name, "||", result.URL)
}
}
Örnek JSON yanıtı
Bing Web Araması API'si yanıtları JSON biçiminde döndürülür. Bu örnek yanıt yapısı kullanılarak BingAnswer
biçimlendirilmiştir ve ve result.URL
değerini result.Name
gösterir.
Microsoft Cognitive Services || https://www.microsoft.com/cognitive-services
Cognitive Services | Microsoft Azure || https://azure.microsoft.com/services/cognitive-services/
What is Microsoft Cognitive Services? | Microsoft Docs || https://learn.microsoft.com/azure/ai-services/Welcome
Microsoft Cognitive Toolkit || https://www.microsoft.com/en-us/cognitive-toolkit/
Microsoft Customers || https://customers.microsoft.com/en-us/search?sq=%22Microsoft%20Cognitive%20Services%22&ff=&p=0&so=story_publish_date%20desc
Microsoft Enterprise Services - Microsoft Enterprise || https://enterprise.microsoft.com/en-us/services/
Microsoft Cognitive Services || https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236
Cognitive Services - msdn.microsoft.com || https://msdn.microsoft.com/magazine/mt742868.aspx