gpt4 book ai didi

Python - 属性错误 : 'NoneType' object has no attribute 'get_text'

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:48 28 4
gpt4 key购买 nike

我正在学习 bs4 的一些教程。我正在尝试使用“a”获取以下示例的 get_text()。教程返回结果 McDermott International 和 MDR 没有问题。但是当我这样做时,我得到了 AttributeError: 'NoneType' object has no attribute 'get_text'。请帮忙。非常感谢!

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&amp;ei=nblKWaDrOs7AmgH0l7S4Bg">McDermott
International</a>
</td>, <td style="text-align:left;">
<a href="/finance?q=NYSE:MDR&amp;ei=nblKWaDrOs7AmgH0l7S4Bg">MDR</a>
</td>, <td style="text-align:left;">
<a href="/finance?q=NYSE:EQT&amp;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 似乎有一些标签不包含 anchor 标签。您需要添加一个条件来妥善处理这些问题:

for stock in energylist:
try:
stock_name = stock.find('a').get_text()
... # more code
except AttributeError:
pass

关于Python - 属性错误 : 'NoneType' object has no attribute 'get_text' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45255709/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com