Python-AttributeError:"NoneType"对象没有属性"get_text" [英] Python - AttributeError: 'NoneType' object has no attribute 'get_text'
本文介绍了Python-AttributeError:"NoneType"对象没有属性"get_text"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在关注bs4的一些教程.我正在尝试使用'a'的以下示例进行get_text().教程返回结果McDermott International和MDR毫无问题.但是,当我得到AttributeError时:'NoneType'对象没有属性'get_text'.请帮忙.非常感谢!
I am following some tutorial for bs4. I am trying to get_text() for below example with 'a'. Tutorial return result McDermott International and MDR without problem. But when I do I got AttributeError: 'NoneType' object has no attribute 'get_text'. Please help. Many thanks!
with open('Energy.htm') as f:
soup = BeautifulSoup(f,"lxml")
energylist = soup.find_all('td', {"style" : "text-align:left;"})
for stock in energylist:
try:
stock_name = stock.find('a').get_text()
except:
stock_name = ''
#sample of the energylist
[<td style="text-align:left;">
<a href="/finance?q=NYSE:MDR&ei=nblKWaDrOs7AmgH0l7S4Bg">McDermott
International</a>
</td>, <td style="text-align:left;">
<a href="/finance?q=NYSE:MDR&ei=nblKWaDrOs7AmgH0l7S4Bg">MDR</a>
</td>, <td style="text-align:left;">
<a href="/finance?q=NYSE:EQT&ei=nblKWaDrOs7AmgH0l7S4Bg">EQT</a>
</td>, <td colspan="8" style="text-align:left;">
Companies <b>1 - 20</b> of about <b>476</b> in <b>Energy</b>
</td>]
推荐答案
energylist
似乎有些标签中不包含锚标签.您需要添加一个条件来优雅地处理这些问题:
It would seem energylist
has some tags that do not contain the anchor tag within them. You'll need to add a condition to handle those gracefully:
for stock in energylist:
try:
stock_name = stock.find('a').get_text()
... # more code
except AttributeError:
pass
这篇关于Python-AttributeError:"NoneType"对象没有属性"get_text"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文