2011-02-09 27 views
0

我想创建一个类的数据抓取文件,我必须刮的数据要求我使用While循环来获取正确的数据到单独的数组 - 即状态和SAT平均等从列表创建字符串的属性错误

但是,一旦我设置了while循环,我认为正则表达式清除了大部分的HTML标签从数据坏了,我得到的是一条错误:

Attribute Error: 'NoneType' object has no attribute 'groups'

我的代码是:

import re, util 
from BeautifulSoup import BeautifulStoneSoup 

# create a comma-delineated file 
delim = ", " 

#base url for sat data 
base = "http://www.usatoday.com/news/education/2007-08-28-sat-table_N.htm" 

#get webpage object for site 
soup = util.mysoupopen(base) 

#get column headings 
colCols = soup.findAll("td", {"class":"vaTextBold"}) 

#get data 
dataCols = soup.findAll("td", {"class":"vaText"}) 

#append data to cols 
for i in range(len(dataCols)): 
    colCols.append(dataCols[i]) 

#open a csv file to write the data to 
fob=open("sat.csv", 'a') 

#initiate the 5 arrays 
states = [] 
participate = [] 
math = [] 
read = [] 
write = [] 

#split into 5 lists for each row 
for i in range(len(colCols)): 
    if i%5 == 0: 
     states.append(colCols[i]) 
i=1 
while i<=250: 
    participate.append(colCols[i]) 
    i = i+5 

i=2 
while i<=250: 
    math.append(colCols[i]) 
    i = i+5 

i=3 
while i<=250: 
    read.append(colCols[i]) 
    i = i+5 

i=4 
while i<=250: 
    write.append(colCols[i]) 
    i = i+5 

#write data to the file 
for i in range(len(states)): 
    states = str(states[i]) 
    participate = str(participate[i]) 
    math = str(math[i]) 
    read = str(read[i]) 
    write = str(write[i]) 

    #regex to remove html from data scraped 

    #remove <td> tags 
    line = re.search(">(.*)<", states).groups()[0] + delim + re.search(">(.*)<",  participate).groups()[0]+ delim + re.search(">(.*)<", math).groups()[0] + delim + re.search(">(.*)<", read).groups()[0] + delim + re.search(">(.*)<", write).groups()[0] 

    #append data point to the file 
    fob.write(line) 

关于为什么这个错误突然出现的任何想法?正则表达式工作正常,直到我试图将数据分成不同的列表。我已经尝试在最后的“for”循环中打印各种字符串,以查看它们中的任何一个对于第一个i值(0)是否为“无”,但它们都是它们应该是的字符串。

任何帮助将不胜感激!

回答

1

它看起来像正则表达式搜索失败(其中之一)的字符串,所以它返回None而不是MatchObject

请尝试以下,而不是很长#remove <td> tags行:

out_list = [] 
for item in (states, participate, math, read, write): 
    try: 
     out_list.append(re.search(">(.*)<", item).groups()[0]) 
    except AttributeError: 
     print "Regex match failed on", item 
     sys.exit() 
line = delim.join(out_list) 

这样一来,就可以找出你的正则表达式失败。

此外,我建议您使用.group(1)而不是.groups()[0]。前者更明确。