首页 > 解决方案 > AttributeError:“NoneType”对象在 beautifulsoup 中没有“find”属性

问题描述

一个月后,我决定再次开发我的应用程序。我打开它并运行它,我得到了这个错误:AttributeError: 'NoneType' object has no attribute 'find'. 我记得它工作得很好,也许有一个beautifulsoup 更新或网站(房地产)改变了什么?但是不,代码是一样的。

根据编译器,这是导致问题的行:

propertyQuantity = soup.find("h1", {"class":"list-result-title"}).find("b", recursive = False).text

如有必要,我可以发布整个代码。你注意到那条线有什么问题吗?

标签: pythonbeautifulsoup

解决方案


soup.find()None如果找不到您指定的元素,则返回。在尝试对结果调用其他方法之前,您需要检查这一点。所以把它分成两个语句:

h1 = soup.find("h1", {"class":"list-result-title"})
if h1:
    property = find("b", recursive = False)
    if property:
        propertyQuantity = property.text
    else:
        // report problem finding `b`
else:
    // report problem finding h1

推荐阅读