Guyana.Hand
Guyana.Hand

Reputation: 67

How do I tell CSV to make a column instead of a row?

I wrote a very simple program with Nokogiri to scrape a website and create a CSV file. It is getting the correct data and making the CSV, but the data is pushed into one cell (A1), and I would rather it come out as a column, with each value separated by a comma.

How do I tell CSV to make a column for each value separated by a comma instead of putting all the info into a single cell?

require 'open-uri'
require 'nokogiri'
require 'csv'

doc = Nokogiri::HTML(open('somewebpage.com'))
CSV.open("webpagedata.csv", "wb") do |csv|
    data = doc.css('.information h3 a').map { |link| link['href']  }
    puts data
    csv << [data]
end

Upvotes: 2

Views: 1256

Answers (1)

matt
matt

Reputation: 79723

The result from doc.css('.information h3 a').map { |link| link['href'] } is already an array, so when you add it to your CSV file you don’t need to wrap it in [...].

Change the line

csv << [data]

to

csv << data

The CSV library deals mainly in rows, so if you want to create a column rather than a row, then you need to add a (single entry) row for each entry of the column:

CSV.open("webpagedata.csv", "wb") do |csv|
  data = doc.css('.information h3 a').map { |link| link['href']  }
  data.each do |entry|
    csv << [entry]
  end
end

Note that in this case you do need the [...] around the entry, as you need to add an array not a single item.

Upvotes: 4

Related Questions