A class for performing searches on the Bing search engine. Attributes ---------- bing_api : BingAPI The Bing API to use for performing searches. Methods ------- __init__(self, subscription_key: str) -> None: Initialize the BingSearch instance with the g
| 12 | RESULT_TARGET_PAGE_PER_TEXT_COUNT = 500 |
| 13 | |
| 14 | class BingAPI: |
| 15 | """ |
| 16 | A class for performing searches on the Bing search engine. |
| 17 | |
| 18 | Attributes |
| 19 | ---------- |
| 20 | bing_api : BingAPI |
| 21 | The Bing API to use for performing searches. |
| 22 | |
| 23 | Methods |
| 24 | ------- |
| 25 | __init__(self, subscription_key: str) -> None: |
| 26 | Initialize the BingSearch instance with the given subscription key. |
| 27 | search_top3(self, key_words: str) -> List[str]: |
| 28 | Perform a search on the Bing search engine with the given keywords and return the top 3 search results. |
| 29 | load_page_index(self, idx: int) -> str: |
| 30 | Load the detailed page of the search result at the given index. |
| 31 | """ |
| 32 | def __init__(self, subscription_key : str) -> None: |
| 33 | """ |
| 34 | Initialize the BingSearch instance with the given subscription key. |
| 35 | |
| 36 | Parameters |
| 37 | ---------- |
| 38 | subscription_key : str |
| 39 | The subscription key to use for the Bing API. |
| 40 | """ |
| 41 | self._headers = { |
| 42 | 'Ocp-Apim-Subscription-Key': subscription_key |
| 43 | } |
| 44 | self._endpoint = "https://api.bing.microsoft.com/v7.0/search" |
| 45 | self._mkt = 'en-US' |
| 46 | |
| 47 | def search(self, key_words : str, max_retry : int = 3): |
| 48 | for _ in range(max_retry): |
| 49 | try: |
| 50 | result = requests.get(self._endpoint, headers=self._headers, params={'q': key_words, 'mkt': self._mkt }, timeout=10) |
| 51 | except Exception: |
| 52 | # failed, retry |
| 53 | continue |
| 54 | |
| 55 | if result.status_code == 200: |
| 56 | result = result.json() |
| 57 | # search result returned here |
| 58 | return result |
| 59 | else: |
| 60 | # failed, retry |
| 61 | continue |
| 62 | raise RuntimeError("Failed to access Bing Search API.") |
| 63 | |
| 64 | def load_page(self, url : str, max_retry : int = 3) -> Tuple[bool, str]: |
| 65 | for _ in range(max_retry): |
| 66 | try: |
| 67 | res = requests.get(url, timeout=15) |
| 68 | if res.status_code == 200: |
| 69 | res.raise_for_status() |
| 70 | else: |
| 71 | raise RuntimeError("Failed to load page, code {}".format(res.status_code)) |