Python:另一个“NoneType”对象没有属性错误 [英] Python : Another 'NoneType' object has no attribute error
问题描述
对于新手练习,我试图在html文件中找到元标记,并提取生成器,以便我这样做:
For a newbie exercise , I am trying to find the meta tag in a html file and extract the generator so I did like this :
Version = soup.find("meta", {"name":"generator"})['content']
,因为我有这个错误:
TypeError: 'NoneType' object has no attribute '__getitem__'
我以为使用异常会纠正它,所以我写道:
I was thinking that working with exception would correct it, so I wrote :
try: Version = soup.find("meta", {"name":"generator"})['content']
except NameError,TypeError:
print "Not found"
我所得到的是同样的错误。
and what I got is the same error.
那么该怎么办?
推荐答案
soup.find()
方法没有找到匹配标签,并返回无
。
The soup.find()
method did not find a matching tag, and returned None
.
[...]
项目访问语法查找 __ getitem __
方法,这是 AttributeError
的源代码:
The [...]
item access syntax looks for a __getitem__
method, which is the source of the AttributeError
here:
>>> None[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
测试无
显式:
Version = soup.find("meta", {"name":"generator"})
if Version is not None:
Version = Version['content']
else:
print "Not found"
如果您使用括号对异常进行分组,则您的异常处理也可以正常工作:
Your exception handling would work too, provided you use parenthesis to group the exceptions:
try:
Version = soup.find("meta", {"name":"generator"})['content']
except (NameError, TypeError):
print "Not found"
没有括号,你告诉Python catch NameError
异常,并将生成的异常对象分配给本地名称 TypeError
。这个除了异常,名称:
语法已经被弃用,因为它可以导致你的情况,你认为你抓住了两个例外。
Without parenthesis you are telling Python to catch NameError
exceptions and assign the resulting exception object to the local name TypeError
. This except Exception, name:
syntax has been deprecated because it can lead to exactly your situation, where you think you are catching two exceptions.
但是,这里的代码不应该抛出一个 NameError
exception;这将是一个单独的问题,更好地通过实例化你的变量来解决;以下内容也同样适用:
However, your code here should not throw a NameError
exception; that'd be a separate problem better solved by instantiating your variables properly; the following would work just as well here:
try:
Version = soup.find("meta", {"name":"generator"})['content']
except TypeError:
# No such meta tag found.
print "Not found"
这篇关于Python:另一个“NoneType”对象没有属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!