Created
October 24, 2016 00:04
-
-
Save bongbongco/822b6b518517ba7850d809bbc44d0c81 to your computer and use it in GitHub Desktop.
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
import urllib | |
import requests | |
from requests.auth import HTTPBasicAuth | |
# Bing API key | |
API_KEY = "" | |
def bing_api(query, source_type = "Web", top = 10, format = 'json'): | |
# set search url | |
query = '%27' + urllib.quote(query) + '%27' | |
# web result only base url | |
base_url = 'https://api.datamarket.azure.com/Bing/SearchWeb/' + source_type | |
url = base_url + '?Query=' + query + '&$top=' + str(top) + '&$format=' + format | |
# create credential for authentication | |
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36" | |
# create auth object | |
auth = HTTPBasicAuth(API_KEY, API_KEY) | |
# set headers | |
headers = {'User-Agent': user_agent} | |
# get response from search url | |
try: | |
page1 = requests.get(ap) | |
response_data = requests.get(url, headers=headers, auth = auth) | |
except requests.exceptions.ConnectionError: | |
r.status_code = "Connection refused" | |
print 'Bing Api Connection refused' | |
sys.exit(0) | |
# decode json response content | |
json_result = response_data.json() | |
return json_result | |
def main(): | |
result = bing_api('bing api test') | |
print result | |
if __name__ == "__main__": | |
main() | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment