python - 如何在 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
解决方案
推荐阅读
- php - LOAD DATA INFILE 不适用于在字段数据中包含编码 JSON 值的 CSV
- java - 处理 lambda 中的已检查异常
- mysql - 使用连接缓冲区(块嵌套循环)对 Extra 列中的 EXPLAIN mysql 命令意味着什么?
- javascript - AJAX Codeigniter 获取模态数据
- java - WAS 9 如何在 Websphere Application Server V9 上覆盖默认提供的 MyFaces2.2
- math - 两个数据集的差异
- javascript - 单击省略号时展开和缩小
- amazon-web-services - 如何使用 kinesis 视频流制作器(WebRTC)从笔记本电脑的摄像头流式传输视频
- python - Keras ValueError:检查输入时出错:预期 anchor_input 有 3 个维度,但得到的数组形状为 (18, 1)
- spring - java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V