使用NewsApi.org开发新闻程序遇导入错误:无法从newsapi导入NewsApiClient
解决NewsApi导入错误及代码问题
导入错误的原因及解决
- 你的脚本文件名为
newsapi.py,和第三方库newsapi重名,Python会优先加载当前目录下的同名文件,而非通过pip安装的官方库,导致找不到NewsApiClient类。 - 解决步骤:
- 将你的脚本重命名(比如改为
apple_news.py),避免和库名冲突。 - 确保已安装官方SDK:执行命令
pip install newsapi-python
- 将你的脚本重命名(比如改为
代码修正方案
方案1:直接用requests请求(无需导入NewsApiClient)
你的代码里存在无用导入和错误变量赋值,修正后:
import requests url = ('https://newsapi.org/v2/everything?' 'q=Apple&' 'from=2023-06-11&' 'sortBy=popularity&' 'apiKey=0e24ed7870d04cc392d0a5804381faf7') response = requests.get(url) if response.status_code == 200: # 解析返回的JSON数据 news_data = response.json() print(news_data) else: print(f"请求失败,状态码:{response.status_code}")
方案2:使用NewsApiClient库(更规范)
如果想用官方提供的SDK简化开发,代码如下:
from newsapi import NewsApiClient # 初始化客户端 newsapi = NewsApiClient(api_key='0e24ed7870d04cc392d0a5804381faf7') # 获取苹果相关新闻 all_articles = newsapi.get_everything( q='Apple', from_param='2023-06-11', sort_by='popularity' ) print(all_articles)
内容的提问来源于stack exchange,提问作者tomthegamer
相关产品推荐
相关产品推荐

