[Solved] Python – AttributeError: ‘NoneType’ object has no attribute ‘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>]
Solution #1:
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
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .