Created
November 7, 2016 11:18
-
-
Save naotokui/3daab47f22af924d79f2c2e2b8b14cb5 to your computer and use it in GitHub Desktop.
Get the number of search results on Bing search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# based on https://gist.github.com/o-tomox/6649758#file-bing_api-py | |
import urllib | |
import requests | |
import json | |
class Bing(object): | |
def __init__(self, key): | |
self.api_key = key | |
def get_num_results(self, query): | |
# Base URL | |
url = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Composite?' | |
# refer to: https://datamarket.azure.com/dataset/bing/search#schema | |
params = { | |
"Query": "'{0}'".format(query), | |
"Sources": "'web+image+video+news+spell'", | |
"Market": "'en-US'" | |
} | |
request_url = url + urllib.urlencode(params) + "&$format=json" | |
response = requests.get(request_url, | |
auth=(self.api_key, self.api_key), | |
headers={'User-Agent': 'My API Robot'}) | |
response = response.json() | |
# TODO: better error handling | |
try: | |
total_num = response["d"]["results"][0]["WebTotal"] | |
return total_num | |
except: | |
return 0 | |
if __name__ == '__main__': | |
key = "<API Key>" | |
q = "pen pineapple apple pen" | |
bing = Bing(key) | |
num_results = bing.web_search(q) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment