python - 使用 NewsAPI.org 通过 HTTP 请求传递多个关键字

标签 python

编辑:对于任何遇到相同问题的人来说,事实证明 top_headlines 不支持多个关键字,这是一个无赖。这是带有“所有内容”而不是“头条新闻”的多个关键字的工作代码。

keywords = ["warriors", "spurs"]

url = ('https://newsapi.org/v2/everything?q=' + ' OR '.join(keywords)) + '&language=en' + '&apiKey=' + api_key + '&pageSize=100'

response = requests.get(url)

这会返回很多,因为,你知道,“一切”。查看“from”和“to”参数以稍微限制返回。

OP 从这里开始

我目前正在尝试从新闻聚合 NewsAPI.org 中获取包含某些关键字的热门文章。

如果我只给它一个关键字,它就可以完美运行,示例代码如下:
keywords = ["trump"]

url = ('https://newsapi.org/v2/top-headlines?q=' + ','.join(keywords)) + '&language=en' + '&apiKey=' + api_key + '&pageSize=100'

response = requests.get(url)

for article in response.json()['articles']:
    print(article['title'])

print(url)

print(response.json()['totalResults'])

但是对于我的一生,我无法弄清楚如何将多个关键字传递给这个请求。我已经尝试了加入列表的所有变体,但它只是不合作。

目标是能够在关键字列表中放入另一个字符串,例如:
keywords = ["trump","bitcoin"]

然后让代码返回包含特朗普或比特币的所有头条新闻。我得到的最接近的是返回包含这两个关键字的标题,但我无法让它返回一个或另一个。

我试过用我能想到的每一种策略('+'、' '、'&'、'&q=' 等)加入这些字符串,但我就是想不通。不知道从这里尝试什么。有小费吗?

最佳答案

News API documentation显示了一种为“Everything”端点执行此操作的方法:

Advanced search is supported here:

...

  • Alternatively you can use the AND / OR / NOT keywords, and optionally group these with parenthesis. Eg: crypto AND (ethereum OR litecoin) NOT bitcoin.

The complete value for q must be URL-encoded.


“头条新闻”的文档中没有此类信息,这似乎暗示 “头条新闻”端点不支持高级搜索 .

关于python - 使用 NewsAPI.org 通过 HTTP 请求传递多个关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772926/

相关文章:

javascript - django include_javascript/use_javascript 和类似的

Python包(报纸)安装错误

python - django-mutant 在 django-admin 中创建模型

Python - 函数内的静态变量

python - 无法编译需要 C99 编译器 (AFAIU) 的 pyethash python 包。错误 - 无法打开包含文件 : 'alloca.h'

python - 创建后追加 Numpy 数组

python - Pandas 枢轴错误 "Exception: Data must be 1-dimensional"

Python:用户字典

python - 命令之间的共享选项和标志

python - 使用 joinload 的 sqlalchemy 查询对于每个新的过滤子句会呈指数减慢