Skip to content

Commit b212276

Browse files
authored
Updated structure and libraries
1 parent 22e8370 commit b212276

File tree

1 file changed

+22
-34
lines changed

1 file changed

+22
-34
lines changed

python/Search/BingWebSearchv7.py

Lines changed: 22 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,44 +3,32 @@
33

44
# -*- coding: utf-8 -*-
55

6-
import http.client, urllib.parse, json
6+
import json
7+
import os
8+
from pprint import pprint
9+
import requests
710

8-
# **********************************************
9-
# *** Update or verify the following values. ***
10-
# **********************************************
11+
# Add your Bing Search V7 subscription key and endpoint to your environment variables.
12+
subscription_key = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY']
13+
endpoint = os.environ['BING_SEARCH_V7_ENDPOINT'] + "/bing/v7.0/search"
1114

12-
# Add your Bing Search V7 subscription key to your environment variables.
13-
subscriptionKey = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY']
15+
# Query term(s) to search for.
16+
query = "Microsoft Cognitive Services"
1417

15-
# Add your Bing Search V7 endpoint to your environment variables.
16-
host = os.environ['BING_SEARCH_V7_ENDPOINT']
17-
path = "/bing/v7.0/search"
18+
# Construct a request
19+
mkt = 'en-US'
20+
params = { 'q': query, 'mkt': mkt }
21+
headers = { 'Ocp-Apim-Subscription-Key': subscription_key }
1822

19-
term = "Microsoft Cognitive Services"
23+
# Call the API
24+
try:
25+
response = requests.get(endpoint, headers=headers, params=params)
26+
response.raise_for_status()
2027

21-
def BingWebSearch(search):
22-
"Performs a Bing Web search and returns the results."
28+
print("\nHeaders:\n")
29+
print(response.headers)
2330

24-
headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
25-
conn = http.client.HTTPSConnection(host)
26-
query = urllib.parse.quote(search)
27-
conn.request("GET", path + "?q=" + query, headers=headers)
28-
response = conn.getresponse()
29-
headers = [k + ": " + v for (k, v) in response.getheaders()
30-
if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")]
31-
return headers, response.read().decode("utf8")
32-
33-
if len(subscriptionKey) == 32:
34-
35-
print('Searching the Web for: ', term)
36-
37-
headers, result = BingWebSearch(term)
38-
print("\nRelevant HTTP Headers:\n")
39-
print("\n".join(headers))
4031
print("\nJSON Response:\n")
41-
print(json.dumps(json.loads(result), indent=4))
42-
43-
else:
44-
45-
print("Invalid Bing Search API subscription key!")
46-
print("Please paste yours into the source code.")
32+
pprint(response.json())
33+
except Exception as ex:
34+
raise ex

0 commit comments

Comments
 (0)