Write to a csv file scrapy

2020-03-01 09:04发布

I want to write to csv file in scrapy

 for rss in rsslinks:
  item = AppleItem()
  item['reference_link'] = response.url
  base_url = get_base_url(response)
  item['rss_link'] = urljoin_rfc(base_url,rss)
  #item['rss_link'] = rss
  items.append(item)
  #items.append("\n")
 f = open(filename,'a+')    #filename is apple.com.csv
 for item in items:
    f.write("%s\n" % item)

My output is this:

{'reference_link': 'http://www.apple.com/'
 'rss_link': 'http://www.apple.com/rss '
{'reference_link': 'http://www.apple.com/rss/'
 'rss_link':   'http://ax.itunes.apple.com/WebObjects/MZStore.woa/wpa/MRSS/newreleases/limit=10/rss.xml'}
{'reference_link': 'http://www.apple.com/rss/'
 'rss_link':  'http://ax.itunes.apple.com/WebObjects/MZStore.woa/wpa/MRSS/newreleases/limit=25/rss.xml'}

What I want is this format:

reference_link               rss_link  
http://www.apple.com/     http://www.apple.com/rss/

5条回答
闹够了就滚
2楼-- · 2020-03-01 09:52

Try tablib.

dataset = tablib.Dataset()
dataset.headers = ["reference_link", "rss_link"]

def add_item(item):    
   dataset.append([item.get(field) for fields in dataset.headers])

for item in items:
    add_item(item)

f.write(dataset.csv)

查看更多
够拽才男人
3楼-- · 2020-03-01 09:54

You need to

  1. Write your header row; then
  2. Write the entry rows for each object.

You could approach it like:

fields = ["reference_link", "rss_link"] # define fields to use
with open(filename,'a+') as f: # handle the source file
    f.write("{}\n".format('\t'.join(str(field) 
                              for field in fields))) # write header 
    for item in items:
        f.write("{}\n".format('\t'.join(str(item[field]) 
                              for field in fields))) # write items

Note that "{}\n".format(s) gives the same result as "%s\n" % s.

查看更多
劫难
4楼-- · 2020-03-01 09:55

This is what worked for me using Python3:

scrapy runspider spidername.py -o file.csv -t csv
查看更多
Root(大扎)
5楼-- · 2020-03-01 09:58

simply crawl with -o csv, like:

scrapy crawl <spider name> -o file.csv -t csv
查看更多
该账号已被封号
6楼-- · 2020-03-01 10:02

Best approach to solve this problem is to use python in-build csv package.

import csv

file_name = open('Output_file.csv', 'w') #Output_file.csv is name of output file

fieldnames = ['reference_link', 'rss_link'] #adding header to file
writer = csv.DictWriter(file_name, fieldnames=fieldnames)
writer.writeheader()
for rss in rsslinks:
    base_url = get_base_url(response)
    writer.writerow({'reference_link': response.url, 'rss_link': urljoin_rfc(base_url, rss)}) #writing data into file.
查看更多
登录 后发表回答