-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbing_search_api.py
59 lines (50 loc) · 2.26 KB
/
bing_search_api.py
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
52
53
54
55
56
57
58
59
'''
This is designed for the new Azure Marketplace Bing Search API (released Aug 2012)
Inspired by https://github.com/mlagace/Python-SimpleBing and
http://social.msdn.microsoft.com/Forums/pl-PL/windowsazuretroubleshooting/thread/450293bb-fa86-46ef-be7e-9c18dfb991ad
'''
import requests # Get from https://github.com/kennethreitz/requests
import string
class BingSearchAPI():
bing_api = "https://api.datamarket.azure.com/Bing/Search/"
def __init__(self, key):
self.key = key
def replace_symbols(self, request):
# Custom urlencoder.
# They specifically want %27 as the quotation which is a single quote '
# We're going to map both ' and " to %27 to make it more python-esque
request = string.replace(request, "'", '%27')
request = string.replace(request, '"', '%27')
request = string.replace(request, '+', '%2b')
request = string.replace(request, ' ', '%20')
request = string.replace(request, ':', '%3a')
return request
def search(self, sources, query, params):
''' This function expects a dictionary of query parameters and values.
Sources and Query are mandatory fields.
Sources is required to be the first parameter.
Both Sources and Query requires single quotes surrounding it.
All parameters are case sensitive. Go figure.
For the Bing Search API schema, go to http://www.bing.com/developers/
Click on Bing Search API. Then download the Bing API Schema Guide
(which is oddly a word document file...pretty lame for a web api doc)
'''
request = sources + '?$format=json'
query = self.replace_symbols(str(query))
request += '&Query=%27' + str(query) + '%27'
for key,value in params.iteritems():
request += '&' + key + '=' + str(value)
request = self.bing_api + request
print request
return requests.get(request, auth=(self.key, self.key))
if __name__ == "__main__":
my_key = "vknjCZkZel4gofUWhubpLS0pXUXLbD5VqzIFgkXUHCg="
query_string = "xbox"
bing = BingSearchAPI(my_key)
params = {
# 'ImageFilters':'"Face:Face"',
# '$format': 'json',
# '$top': 10,
# '$skip': 0
}
print bing.search('Web',query_string,params).json() # requests 1.0+