【问题标题】:How to implement Bing News Search API via MS Cognitive Search into a website如何通过 MS 认知搜索将 Bing 新闻搜索 API 实施到网站中
【发布时间】:2023-03-22 10:11:01
【问题描述】:

我对 API 有点不知所措,但我相信这是我需要的代码 这是一个 python 程序,通过 Microsoft 认知服务调用 Bing 新闻搜索 API,这是调用 API 的新方法。我的问题是如何将结果实现/嵌入到我的实际网站中(由 html、css、js 和 server.js 文件组成)?基本上,哪些部分需要去哪里?我非常感谢你能给我的任何帮助。谢谢!

import requests, requests.utils
from py_ms_cognitive_search import PyMsCognitiveSearch

##
##
## News Search
##
##

class PyMsCognitiveNewsException(Exception):
pass

class PyMsCognitiveNewsSearch(PyMsCognitiveSearch):

SEARCH_NEWS_BASE = 'https://api.cognitive.microsoft.com/bing/v5.0/news/search'

def __init__(self, api_key, query, safe=False, custom_params=''):
    query_url = self.SEARCH_NEWS_BASE + custom_params
    PyMsCognitiveSearch.__init__(self, api_key, query, query_url, safe=safe)

def _search(self, limit, format):
    '''
    Returns a list of result objects, with the url for the next page MsCognitive search url.
    '''
    payload = {
      'q' : self.query,
      'count' : '50', #currently 50 is max per search.
      'offset': self.current_offset,
      #'mkt' : 'en-us', #optional
      #'safesearch' : 'Moderate', #optional
    }
    headers = { 'Ocp-Apim-Subscription-Key' : self.api_key }
    response = requests.get(self.QUERY_URL, params=payload, headers=headers)
    json_results = self.get_json_results(response)

    packaged_results = [NewsResult(single_result_json) for single_result_json in json_results["value"]]
    self.current_offset += min(50, limit, len(packaged_results))
    return packaged_results

class NewsResult(object):
'''
The class represents a SINGLE news result.
Each result will come with the following:
the variable json will contain the full json object of the result.
category: category of the news
name: name of the article (title)
url: the url used to display.
image_url: url of the thumbnail
date_published: the date the article was published
description: description for the result
Not included: about, provider, mentions
'''

def __init__(self, result):
    self.json = result
    self.category = result.get('category')
    #self.about = result['about']
    self.name = result.get('name')
    self.url = result.get('url')
    try:
        self.image_url = result['image']['thumbnail']['contentUrl']
    except KeyError as kE:
        self.image_url = None
    self.date_published = result.get('datePublished')
    self.description = result.get('description')

【问题讨论】:

    标签: python api search bing


    【解决方案1】:

    _search 函数返回一个结果列表(packaged_results)。如果您想在网站中显示这些内容,则必须使用 Python 脚本加载/呈现 html 文件。这就是像 Django 这样的框架派上用场的地方,其中使用了视图和模板。

    Django中搜索页面的基本视图(进入应用程序的views.py模块):

    def search(request):
        result_list = []
    
        if request.method=='POST':
            query = request.POST['query'].strip()
            if query:
                result_list = _search(query)
    
        return render(request, 'web/search.html', {'result_list': result_list})
    

    在 search.html 模板的正文中(使用 Django 模板语言,以及每个新闻结果的问题作者类):

    <div>
            {% if result_list %}
            <h3>Results</h3>
            <!-- Display search results -->
            <div>
                {% for result in result_list %}
                <div>
                    <h4>
                        {{ result.category }}</a>
                    </h4>
                    <p>{{ result.about }}</p>
                </div>
                {% endfor %}
            </div>
            {% endif %}
    </div>
    

    如果您希望使用 Django 来解决这个特定问题,这里是关于编写视图的文档和另一个用于 Django 模板的文档,它们都是 HTML 文件。

    https://docs.djangoproject.com/en/1.10/topics/http/views/

    https://docs.djangoproject.com/en/1.10/topics/templates/

    【讨论】:

    • 仅仅发布链接对任何人都没有帮助。尝试将代码的相关 sn-ps 包含在您的答案中。
    • 感谢您的建议。我做了一些修改。
    最近更新 更多