【发布时间】: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:你去吧!