属性错误:'NoneType'对象没有'encode'属性
我正在用Python获取网址并对它们进行修改。错误发生在这里:
for link in soup.findAll('a'):
linkori = (link.get('href'))
print 'LINKORI : %s' %linkori
fonte1 = linkori
fonte1 = str(fonte1.encode('utf8'))
这是我的错误追踪信息:
File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec codeObject in __main__.__dict__
File "F:\Docs\Projti\Rafael\Python Scripts\final.py", line 258, in <module>
fonte1 = str(fonte1.encode('utf8'))
AttributeError: 'NoneType' object has no attribute 'encode'
我尝试过使用 .join
或其他方法,但总是出现同样的错误。当我打印 linkori
时,它能完美显示来自 link.get
的网址。有人能告诉我哪里出错了吗?
1 个回答
1
.get()
方法如果找不到 href
属性,就会返回 None
,也就是说什么都没有。为了避免这种情况,建议你只查找那些带有 href
属性的 <a>
标签:
for link in soup.findAll('a', href=True):
linkori = link['href']
fonte1 = linkory.encode('utf8')