Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import urllib
import requests
import json
class Bing(object):
def __init__(self, key):
self.api_key = key
def web_search(self, query, k, keys=["Url"], skip=0):
url = 'https://api.datamarket.azure.com/Bing/Search/Web?'
max_response_count = 50
params = {
"Query": "'{}'".format(query),
"Market": "'{}'".format('ja-JP'),
"Adult": "'{}'".format('Strict')
}
request_url = url + urllib.parse.urlencode(params) + "&$format=json"
results = []
repeat = int(k / max_response_count)
remainder = int(k % max_response_count)
for i in range(repeat):
result = self._search(request_url, max_response_count, skip, keys)
results.extend(result)
skip += max_response_count
if remainder:
result = self._search(request_url, remainder, skip, keys)
results.extend(result)
return results
def related_search(self, query, keys=["Title"]):
url = 'https://api.datamarket.azure.com/Bing/Search/RelatedSearch?'
params = {
"Query": "'{}'".format(query),
"Market": "'{}'".format('ja-JP')
}
request_url = url + urllib.parse.urlencode(params) + "&$format=json"
results = self._search(request_url, 50, 0, keys)
return results
def _search(self, request_url, top, skip, keys):
url = "{0}&$top={1}&$skip={2}".format(request_url, top, skip)
response = requests.get(url, auth=('', self.api_key)).json()
results = []
for item in response['d']['results']:
result = {}
for key in keys:
result[key] = item[key]
results.append(result)
return results
if __name__ == '__main__':
key = 'API KEY'
q = '-site:http://www.aikatsu.com/stars/ アイカツ'
bing = Bing(key)
results = bing.web_search(q, 10, ['Title', 'Url', 'Description'])
for result in results:
print(result)
results = bing.related_search(q)
for result in results:
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment