【发布时间】: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表,所以statement是None。有趣的是,我无法使用您提供给我们的 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