Вопрос

I wounder how I can save the parsed data to a txt file. My script is only saving the last parsed. Do i need to add .each do ? kind of lost right now

here is my code and if maybe somebody could explain to me how save the parsed info on a new line

here is the code

require 'rubygems'
require 'nokogiri'
require 'open-uri'

url = "http://www.clearsearch.se/foretag/-/q_advokat/1/"
doc = Nokogiri::HTML(open(url))

doc.css(".gray-border-bottom").each do |item|
  title = item.css(".medium").text.strip
  phone = item.css(".grayborderwrapper > .bold").text.strip
  adress = item.css(".grayborder span").text.strip
  www = item.css(".click2www").map { |link| link['href'] }

  puts "#{title} ; \n"
  puts "#{phone} ; \n"
  puts "#{adress} ; \n"
  puts "#{www} ; \n\n\n"

  puts "Writing"
  company = "#{title}; #{phone}; #{adress}; #{www} \n\n"
  puts "saving"
  file = File.open("exporterad.txt", "w") 
  file.write(company)
  file.close
  puts "done"
end
puts "done"
Это было полезно?

Решение

Calling File.open inside your loop truncates the file to zero length with each invocation. Instead, open the file outside your loop (using the block form):

File.open("exporterad.txt", "w") do |file|
  doc.css(".gray-border-bottom").each do |item|
    # ...
    file.write(company)
    # ...
  end
end # <- file is closed automatically at the end of the block
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top