|
3 | 3 |
|
4 | 4 | # -*- coding: utf-8 -*- |
5 | 5 |
|
6 | | -import http.client, urllib.parse, json |
| 6 | +import json |
| 7 | +import os |
| 8 | +from pprint import pprint |
| 9 | +import requests |
7 | 10 |
|
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" |
11 | 14 |
|
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" |
14 | 17 |
|
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 } |
18 | 22 |
|
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() |
20 | 27 |
|
21 | | -def BingWebSearch(search): |
22 | | - "Performs a Bing Web search and returns the results." |
| 28 | + print("\nHeaders:\n") |
| 29 | + print(response.headers) |
23 | 30 |
|
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)) |
40 | 31 | 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