我正在关注bs4的一些教程。我正在尝试使用'a'的以下示例进行get_text()。教程返回结果McDermott International和MDR毫无问题。但是,当我得到AttributeError时:'NoneType'对象没有属性'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中有一些不包含锚标签的标签。您需要添加一个条件来妥善处理这些条件:

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

关于python - Python-AttributeError:“NoneType”对象没有属性“get_text”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45255709/

10-12 18:46