【问题标题】:TypeError: writerows() argument must be iterableTypeError:writerows() 参数必须是可迭代的
【发布时间】:2014-08-06 20:50:47
【问题描述】:

Python 2.7

我正在尝试获取此页面上的公司名称并将它们保存在 csv 文件中。

我的代码的第一部分工作正常,但每个返回的对象(公司名称)之间都有空格。

我在编写结果并将其保存在 csv 文件中时也遇到了麻烦,这让我相信这是因为之间的空间使“数据”不可迭代。

有人可以帮助修正语法吗?非常感谢!

我的代码(第一部分)

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

【问题讨论】:

  • print_all_com 中没有返回语句,所以data 可能是None

标签: python python-2.7 web-crawler urllib2 export-to-csv


【解决方案1】:

我无法测试它,但可能应该是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    相关资源
    最近更新 更多