简体   繁体   中英

Running a Bing API search in Python multiple times

I'm making a program that can search Bing for number of articles in a certain time frame (such as a day or a week) when searching by a certain country code. However, I'm trying to search for each query in a list while rerunning the program for each one and storing the results for each in another list so I can analyze the data later. Code so far is as follows:

countries = ["AR","AU","BR","CA",...]
numbers = []
combinedList= []
subscription_key = "XXXXXXXXXXX"
assert subscription_key
search_url = "https://api.cognitive.microsoft.com/bing/v7.0/search"
search_term = "G20"
headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
params = {"q": search_term, "cc": countries, "freshness":"Day"}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()
totalRes = search_results["webPages"]['totalEstimatedMatches']
numbers.append(totalRes)

The "cc" section of line 9 is where you would normally try to put in the 2-digit code but I'm trying to do all of them individually.

Thank you in advance!

Try this:

countries = ["AR","AU","BR","CA",...]
numbers = []
combinedList= []
subscription_key = "XXXXXXXXXXX"
assert subscription_key
search_url = "https://api.cognitive.microsoft.com/bing/v7.0/search"
search_term = "G20"
headers = {"Ocp-Apim-Subscription-Key" : subscription_key}

for country in countries:
    params = {"q": search_term, "cc": country, "freshness":"Day"}
    response = requests.get(search_url, headers=headers, params=params)
    response.raise_for_status()
    search_results = response.json()
    totalRes = search_results["webPages"]['totalEstimatedMatches']
    numbers.append(totalRes)

You just needed to loop over the countries. Since the array countries contains strings, so will the variable country in the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM