Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3.7密钥错误_Python_Keyerror - Fatal编程技术网

Python3.7密钥错误

Python3.7密钥错误,python,keyerror,Python,Keyerror,我喜欢从NewsApi检索信息,但遇到了一个问题。随函附上代码: from NewsApi import NewsApi import pandas as pd import os import datetime as dt from datetime import date def CreateDF(JsonArray,columns): dfData = pd.DataFrame() for item in JsonArray: itemStruct =

我喜欢从NewsApi检索信息,但遇到了一个问题。随函附上代码:

from NewsApi import NewsApi
import pandas as pd
import os
import datetime as dt
from datetime import date


def CreateDF(JsonArray,columns):
    dfData = pd.DataFrame()

    for item in JsonArray:
        itemStruct = {}

        for cunColumn in columns:
            itemStruct[cunColumn] = item[cunColumn]

        # dfData = dfData.append(itemStruct,ignore_index=True)
            # dfData = dfData.append({'id': item['id'], 'name': item['name'], 'description': item['description']},
            #                        ignore_index=True)

    # return dfData
    return itemStruct

def main():
    # access_token_NewsAPI.txt must contain your personal access token
    with open("access_token_NewsAPI.txt", "r") as f:
        myKey = f.read()[:-1]
        #myKey = 'a847cee6cc254d8495632f83d5c77d39'

    api = NewsApi(myKey)

    # get sources of news
    # columns = ['id', 'name', 'description']
    # rst_source = api.GetSources()
    # df = CreateDF(rst_source['sources'], columns)
    # df.to_csv('source_list.csv')
    #
    #
    # # get news for specific country
    # rst_country = api.GetHeadlines()
    # columns = ['author', 'publishedAt', 'title', 'description','content', 'url']
    # df = CreateDF(rst_country['articles'], columns)
    # df.to_csv('Headlines_country.csv')

    # get  news for specific symbol
    symbol = "coronavirus"
    sources = 'bbc.co.uk'
    columns = ['author', 'publishedAt', 'title', 'description', 'content', 'source']
    limit = 500     # maximum requests per day
    i = 1
    startDate = dt.datetime(2020, 3, 1, 8)
    # startDate = dt.datetime(2020, 3, 1)
    df = pd.DataFrame({'author': [], 'publishedAt': [], 'title': [], 'description': [], 'content':[], 'source': []})
    while i < limit:
        endDate = startDate + dt.timedelta(hours=2)
        rst_symbol = api.GetEverything(symbol, 'en', startDate, endDate, sources)
        rst = CreateDF(rst_symbol['articles'], columns)
        df = df.append(rst, ignore_index=True)
        # DF.join(df.set_index('publishedAt'), on='publishedAt')
        startDate = endDate
        i += 1

    df.to_csv('Headlines_symbol.csv')

main()
在这方面:

rst = CreateDF(rst_symbol['articles'], columns)
我认为关于密钥没有被找到或定义存在一些问题-有人知道如何解决这个问题吗?我感谢每一个提示

梅尼亚克

编辑:

在我尝试了你的一些提示之后,我找到了解决办法。显然,当NewsAPI密钥遇到请求限制时发生了错误。每次都会发生这种情况,直到我将
limit=500
更改为
limit=20
。由于某些原因,新的API密钥和减少的限制没有错误


谢谢你们的帮助,伙计们

可能“articles”不是rst\u symbol对象中的列。

python没有提到任何名为
NewsApi()
GetEverything()
的方法,而是
NewsApiClient()
get\u everything()
,即:

from newsapi import NewsApiClient

# Init
newsapi = NewsApiClient(api_key='xxx')

# /v2/top-headlines
top_headlines = newsapi.get_top_headlines(q='bitcoin',
                                          sources='bbc-news,the-verge',
                                          category='business',
                                          language='en',
                                          country='us')

# /v2/everything
all_articles = newsapi.get_everything(q='bitcoin',
                                      sources='bbc-news,the-verge',
                                      domains='bbc.co.uk,techcrunch.com',
                                      from_param='2017-12-01',
                                      to='2017-12-12',
                                      language='en',
                                      sort_by='relevancy',
                                      page=2)

# /v2/sources
sources = newsapi.get_sources()

正如错误所说的那样,
KeyError:“articles”
。您正在访问字典中不存在的位置。让它存在<代码>rst_符号['articles']={}或对象,请阅读文档
api.get_everything()
不是
api.GetEverything()
,它似乎是来自其他编程语言的方法名。请提供完整的错误消息,以及。另外,您能澄清问题的具体内容吗?我创建了对象类NewsApi,然后将其读入。我找到了解决方案,并把它放到了原来的帖子里!谢谢你帮助我!不客气,很高兴你把问题解决了,但是你应该发布一个答案,而不是更新你的问题。
from newsapi import NewsApiClient

# Init
newsapi = NewsApiClient(api_key='xxx')

# /v2/top-headlines
top_headlines = newsapi.get_top_headlines(q='bitcoin',
                                          sources='bbc-news,the-verge',
                                          category='business',
                                          language='en',
                                          country='us')

# /v2/everything
all_articles = newsapi.get_everything(q='bitcoin',
                                      sources='bbc-news,the-verge',
                                      domains='bbc.co.uk,techcrunch.com',
                                      from_param='2017-12-01',
                                      to='2017-12-12',
                                      language='en',
                                      sort_by='relevancy',
                                      page=2)

# /v2/sources
sources = newsapi.get_sources()