RUBY
1require 'bundler/setup' 2require 'open-uri' 3require 'nokogiri' 4require 'csv' 5require 'pry-byebug' 6**ボールドテキスト** 7begin 8bom = %w(EF BB BF).map { |e| e.hex.chr }.join 9csv_file = CSV.generate(bom) do |csv| 10 11end 12 13File.open("sample1.csv", "w") do |file| 14file.write(csv_file) 15end 16 17 18def get_parsed_html(url) 19 html = open(url) do |f| 20 charset = f.charset 21 f.read 22 end 23 24 Nokogiri::HTML.parse(html,nil,'utf-8') 25end 26 27path = "./lib/sample.csv" 28url_array = Array.new 29CSV.foreach(path) do |row| 30 url_array << row[0] 31end 32i = 1 33url_array.each do |url| 34 35doc = get_parsed_html(url) 36 37doc.css('body > div:nth-child(9) > section.product-details > div > section > div.product-details__image').each do |total| 38 random = Random.new 39 sleep(random.rand(1..3)) #1〜3秒待つ 40 41 cards = [] 42 i = i + 1 43 number = i 44 name = total.css('img').attribute('alt').value 45 img = total.css('img').attribute('src').value 46 img_name = "0412#{number}.jpg" 47 48 cards << name 49 cards << img_name 50 p cards 51 52 filename = "./lib/img/#{img_name}" 53 54 open(filename, 'wb') do |file| 55 open(img) do |data| 56 file.write(data.read) 57 p filename 58 end 59 end 60 CSV.open("sample1.csv", "a") do |file| 61 file << cards 62 end 63rescue => e 64 p "error" 65 CSV.open("sample1.csv", "a") do |file| 66 file << ["error"] 67 end 68 69end 70end 71end
ファイル名は適当にsampleにしてあります。
エラーで
`open_http': 404 Not Found (OpenURI::HTTPError)
が発生した場合どこにbeginrescueendを書けば良いでしょうか?
ご教示お願いいたします
回答1件
あなたの回答
tips
プレビュー