类型对象不可下标-python

Luc*_*jee 0 python python-3.x

 from newsapi.sources import Sources
 import json
 api_key ='*******************'
 s = Sources(API_KEY=api_key)
Run Code Online (Sandbox Code Playgroud)

他们输入他们想要的新闻类别

 wanted = input('> ')
 source_list = s.get(category=wanted, language='en')

 index = 0
 sources = []
Run Code Online (Sandbox Code Playgroud)

获取 source_list["sources"] 中 source 的来源:

     data = json.dumps(source_list)
     data = json.loads(data)

     source = (data["sources"][index]["url"])
     sources.append(source)
     index += 1


 from newspaper import Article

 i = len(sources) - 1
Run Code Online (Sandbox Code Playgroud)

循环遍历源列表并打印源中源的文章:

     url_ = sources[i]

     a = Article[url_]  
     print(a)

     i -= 1
Run Code Online (Sandbox Code Playgroud)

得到错误 'type' object is not subscriptable on the linea = Article[url_]已经研究过,但在我的情况下仍然不明白为什么。

Mat*_*ory 9

您的问题的简单解决方案是该行:

a = Article[url_]
Run Code Online (Sandbox Code Playgroud)

应该:

a = Article(url_)
Run Code Online (Sandbox Code Playgroud)

现在来了解为什么会TypeError: 'type' object is not subscriptable出现错误。

TypeError当您object[key]在对象未定义__getitem__方法的情况下使用方括号表示法时,这是由 python 抛出的。例如,[]在object抛出时使用:

>>> object()["foo"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'object' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)

在这种情况下[],()在尝试实例化类时意外使用了s而不是s。大多数类(包括此类Article)都是该类的实例type,因此尝试object["foo"]会导致您遇到的相同错误:

>>> object["foo"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)