いつも勉強させて頂いております。
表題の詳細ですが、
nokogiriを利用してwebスクレイピングの勉強をしています。
テキストファイルの行ごとにURLを記載し、
1行ずつ読み取って該当URLからタイトルを取得するプログラムを作成しています。
1行のみ記載し、プログラムを実行した場合は、正常に結果が出るのですが、
複数行の場合、最後に記載した行以外のタイトルを取得することができません。
また、複数行のURLが同一の場合でも、同様の症状が出ています。
改善に向けたヒントなどでもよいのでアドバイス頂けないでしょうか?
rubyは勉強中の初心者ですので、記載誤りもあるかと思いますが、ご教授お願い致します。
txt
1テキストファイル 2 3https://www.yahoo.co.jp 4https://www.yahoo.co.jp 5https://www.yahoo.co.jp
ruby
1require 'open-uri' 2require 'open_uri_redirections' 3require 'nokogiri' 4 5File.open 'out.txt', 'w' do |out| 6 File.open('url-data.txt') do |f| 7 f.each_line do |line| 8 begin 9 doc = Nokogiri::HTML(open(line, :allow_redirections => :all)) 10 unless doc.title.nil? 11 title_name = doc.title 12 out.write line.rstrip + "\t" + title_name + "\n" 13 sleep(0.5) 14 else 15 out.write line.rstrip + "\t" + "no title\n" 16 sleep(0.5) 17 end 18 rescue 19 out.write line.rstrip + "\t" + "error\n" 20 end 21 end 22 end 23end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/18 07:01