【问题标题】:NoneType AttributeError with multiple html files带有多个 html 文件的 NoneType AttributeError
【发布时间】:2013-03-13 21:05:01
【问题描述】:

我正在尝试从financialStatement 表中找到tr 标记。一切正常,直到我编码最后一行 rows = statement.findAll ( 'tr' ),它给出:

AttributeError: 'NoneType' object has no attribute 'findAll'

这里是html文件:http://investing.businessweek.com/research/stocks/financials/financials.asp?ticker=TSCO:LN

import os
import urllib,re
from BeautifulSoup import BeautifulSoup 

path = '/Users/projectfile/'
listing = os.listdir(path)

for infile in listing:
    print "current file is: " + infile
    fileIN = open(path+infile, "r")
    line = fileIN.read()
    soup = BeautifulSoup ( line )
    statement = soup.find ( 'table' , { 'class' : "financialStatement" })
    rows = statement.findAll ( 'tr' )

【问题讨论】:

  • 找不到financialStatement 表,所以statementNone。有趣的是,我无法使用您提供给我们的 URL 重现该问题。
  • 您不知道find 可以在没有找到任何内容的情况下返回None(这意味着您需要一些错误处理,例如if not statement: continue)?或者您知道这一点,但没想到find 在这种情况下会失败,因此您需要帮助查看 HTML/soup.find 调用?
  • 附带说明一下,将整个文档的内容称为line 非常具有误导性。
  • 同时,您使用的是哪个版本的 BeautifulSoup 和 Python?你确定那是它失败的文件吗?因为当我在 Python 2.7.2 下尝试使用 BS 3.2.1 或 4.1.3 时,或者在 3.3.0 下尝试使用 4.1.3 (处理字符集的小改动)时,他们都成功地找到了一个有 25 行的表。

标签: python file web-scraping beautifulsoup nonetype


【解决方案1】:

这意味着statement 在无。所以可能这一行:soup.find ( 'table' , { 'class' : "financialStatement" }) 没有找到任何东西并返回 None。

您可以添加一个 if 语句来测试 if 语句是否有值:

if statement:
   rows = statement.findAll ( 'tr' )
else:
   rows = None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-07-25
    • 2018-11-12
    • 2021-06-05
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多