TypeError: writerows() 参数必须是可迭代的
我在用Python 2.7
我想从这个页面上获取公司名称,并把它们保存到一个csv文件里。
我代码的第一部分运行得很好,但每个返回的公司名称之间有空格。
我在写结果并保存到csv文件时也遇到了麻烦,这让我觉得可能是因为这些空格导致'data'无法被处理。
有没有人能帮我修正一下语法?非常感谢!
我的代码(第一部分)
import urllib2
response = urllib2.urlopen('http://app.core-apps.com/weftec2014/exhibitors/list/A')
page = response.read()
page = page[4632:]
def get_next_target(page):
start_link = page.find("<a href='/weftec2014/exhibitors/")
if start_link == -1:
return None, 0
else:
start_place = start_link+73 #to get company names after the first <div>
end_place = page.find("</div>", start_place)
item = page[start_place:end_place]
return item, end_place
def print_all_com(page): #return company names
while True:
item, end_place = get_next_target(page)
if item:
print item
page = page[end_place:]
else:
break
data = print_all_com(page)
第二部分(CSV写入器)
import csv
with open('weftec_list.csv','w') as f:
writer = csv.writer(f)
writer.writerows(data)
错误信息:
Traceback (most recent call last):
File "/Users/yumiyang/Documents/MCComponenet_crawler.py", line 32, in <module>
writer.writerows(data)
TypeError: writerows() argument must be iterable
1 个回答
2
我不能测试这个,但它可能应该是:
def print_all_com(page): #return company names
results = []
while True:
item, end_place = get_next_target(page)
if item:
results.append( [ item.strip() ] )
#print item
page = page[end_place:]
else:
break
return results