Skip to main content
 首页 » 编程设计

python之CSV 在单个 csv 字段中的单个列表中写入多个项目

2025年05月04日8kenshinobiy

我想在每个 csv 字段中写入多个列表。其中一个列表包含多个项目。我想将该列表中的项目写在单个 csv 字段中。但我做不到。我的代码是:

def __init__(self): 
    self.myCSV = csv.writer(open('office-ves_04112014.csv', 'wb'),dialect="excel",quotechar='"', quoting=csv.QUOTE_ALL) 
    self.myCSV.writerow(['location','h1','count','urllist']) 
 
def process_item(self, item, spider): 
 self.myCSV.writerow([item['location'][0].encode('utf-8'),item['h1'][0].encode('utf-8'),item['count'], item['url']]) 
 return item 

我正在使用 scrapy 生成 csv 文件的代码。 urllist 是包含多个项目的必需列表。当前代码在单个字段中返回整个列表:

[u'urllistitem1', u'urllistitem2', u'urllistitem3'] 

这不是我想要的。预期的输出是:

urllistitem1,urllistitem2,urllist3 

我的爬虫代码是:

class MyItem(Item): 
 url = Field() 
 location = Field() 
 h1 = Field() 
 count = Field() 
 
 
class MySpider(BaseSpider): 
 name = "officevesdetail" 
 allowed_domains = ["xyz.nl"] 
 f = open("officelist-ves.txt") 
 start_urls = [url.strip() for url in f.readlines()] 
 f.close() 
 
 def parse(self, response): 
  item = MyItem() 
  sel = Selector(response) 
  item['url'] = sel.xpath('//div[@class="text"]/h3/a/@href').extract() 
  item['h1'] = sel.xpath("//h1[@class='no-bd']/text()").extract() 
  item['count'] = len(item['url']) 
  item['location'] = sel.xpath('//input[@name="Location"]/@value').extract() 
  yield item 

如果我尝试

item['url'][0].encode('utf-8') 

我只得到第一个 url 即 urllistitem1

请您参考如下方法:

你给 csv 编写器的最后一个参数向它发送了一个项目列表而不是一个字符串。我猜这是因为您不知道列表的长度。没问题:您已经向它发送了一个列表,因此只需将两个列表加在一起,最好是在对第二个列表的所有元素进行编码之后:

def process_item(self, item, spider): 
    self.myCSV.writerow([item['location'][0].encode('utf-8'), 
                         item['h1'][0].encode('utf-8'), 
                         item['count']] +  
                        [i.encode('utf-8') for i in item['url']]]) 
    return item