首页 > 解决方案 > 如何在 R 中使用 Bing 实体 API 搜索

问题描述

我正在复制此答案中的代码结果:R: How to use Bing free tier web search using R,但是由于给出了该答案,因此 Bing API 已更新。

我能够在 Python 中复制 Microsoft 网站上给出的示例的结果,但未能将其转换为 R。

这是 Python 示例(有效)

import http.client
import urllib.parse
import json

subscriptionKey = 'xxxxxxxxxxx'
host = 'api.bing.microsoft.com'
path = '/v7.0/entities'
mkt = 'en-US'
query = 'Wallmart'
params = '?mkt=' + mkt + '&q=' + urllib.parse.quote (query)


def get_suggestions ():
 headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
 conn = http.client.HTTPSConnection (host)
 conn.request ("GET", path + params, None, headers)
 response = conn.getresponse ()
 return response.read()


result = get_suggestions ()
print (json.dumps(json.loads(result), indent=4))

这就是我能够在 R 中获得相同结果的方式

library(httr)

server = "api.bing.microsoft.com"
path = '/v7.0/entities'
token = "xxxxxxx"
mkt = "en-US"
query = "Wallmart"
params = paste0("?mkt=", mkt, "&q=", query)


url = paste0(server,path,"search")

response = GET(url = url, 
               query = list(q = params), 
               add_headers(`Ocp-Apim-Subscription-Key` = token)
)

这只是给我一个错误:此处解释的Error in curl::curl_fetch_memory(url, handle = handle) : Protocol "" not supported or disabled in libcurl其他基本命令: https : //cran.r-project.org/web/packages/httr/vignettes/quickstart.html 确实有效。GET()

回答

好的,我问这个问题有点快。我得到了答案,1)使用莫里斯的建议,2)改变查询。

library(httr)

server = "https://api.bing.microsoft.com"
path = '/v7.0/entities/'
token = "xxxxxxx"
mkt = "en-US"
query = "Wallmart"


url = paste0(server,path)

response = GET(url = url, 
              query = list(mkt = mkt,
                            q = query), 
              add_headers(`Ocp-Apim-Subscription-Key` = token)
)


res = content(response, encoding = "json")
res

标签: pythonrazurehttr

解决方案


推荐阅读