File size: 1,697 Bytes
09321b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
import os

import json
import requests
from ..search_util import (
    AuthenticationKey, SearchResult)

from .base_searcher import WebSearcher


class BingWebSearcher(WebSearcher):

    def __init__(
        self,
        timeout=3000,
        mkt='en-US',
        endpoint='https://api.bing.microsoft.com/v7.0/search',
    ):
        self.mkt = mkt
        self.endpoint = endpoint
        self.timeout = timeout
        self.token = os.environ.get(AuthenticationKey.bing)

    def __call__(self, query, **kwargs):
        params = {'q': query, 'mkt': self.mkt}
        headers = {'Ocp-Apim-Subscription-Key': self.token}
        if kwargs:
            params.update(kwargs)
        try:
            response = requests.get(
                self.endpoint,
                headers=headers,
                params=params,
                timeout=self.timeout)
            raw_result = json.loads(response.text)
            if raw_result.get('error', None):
                print(f'Call Bing web search api failed: {raw_result}')
        except Exception as ex:
            raise ex('Call Bing web search api failed.')

        results = []
        res_list = raw_result.get('webPages', {}).get('value', [])
        for item in res_list:
            title = item.get('name', None)
            link = item.get('url', None)
            sniper = item.get('snippet', None)
            if not link and not sniper:
                continue

            results.append(SearchResult(title=title, link=link, sniper=sniper))

        return results


if __name__ == '__main__':

    searcher = BingWebSearcher()
    res = searcher('哈尔滨元旦的天气情况')
    print([item.__dict__ for item in res])