gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:05:55 25 4
gpt4 key购买 nike

编辑:对于任何遇到相同问题的人来说,事实证明 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com