【问题标题】:CSV write multiple items in a single list in single csv fieldCSV 在单个 csv 字段的单个列表中写入多个项目
【发布时间】:2014-04-11 10:11:04
【问题描述】:

我有多个列表,我想在每个 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')

我只得到第一个网址,即 urllistitem1

【问题讨论】:

  • 你的问题有点不清楚。您指的是 urllist,但这仅称为标题行的文本。调用 writerow 时,您不会在任何地方使用它作为变量。
  • 发布带有明确 URL 和示例输出的完整蜘蛛代码将使这更容易理解和尝试排除故障。 :)
  • @Talvalin:你去吧!

标签: python csv scrapy


【解决方案1】:

您给 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

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2021-01-03
    • 2018-11-04
    相关资源
    最近更新 更多