0

これが私のコードです..

require "open-uri"

base_url = "http://en.wikipedia.org/wiki"

(1..5).each do |x|
  # sets up the url
  full_url = base_url + "/" + x.to_s
  # reads the url
  read_page = open(full_url).read
  # saves the contents to a file and closes it
  local_file = "my_copy_of-" + x.to_s + ".html"
  file = open(local_file,"w")
  file.write(read_page)
  file.close

  # open a file to store all entrys in

  combined_numbers = open("numbers.html", "w")

  entrys = open(local_file, "r")

  combined_numbers.write(entrys.read)

  entrys.close
  combined_numbers.close

end

ご覧のように。基本的には、ウィキペディアの記事 1 から 5 までのコンテンツをスクレイピングし、それらを numbers.html という 1 つのファイルに結合しようとします。

それは最初のビットを正しく行います。しかし、2番目になると。ループの5番目の記事の内容に書き込むだけのようです。

どこが間違っているのかわかりません。何か助けはありますか?

4

1 に答える 1

2

概要ファイルを開くときに間違ったモードを選択しました。「w」は既存のファイルを上書きし、 「a」は既存のファイルに追加します

したがって、これを使用してコードを機能させます。

combined_numbers = open("numbers.html", "a")

それ以外の場合は、ループを通過するたびに、 numbers.htmlのファイルの内容が現在の記事で上書きされます。


さらに、書きたてのファイルから内容を読み戻すのではなく、内容を使用しread_pageて書き込む必要があると思います。numbers.html

require "open-uri"

(1..5).each do |x|
  # set up and read url
  url = "http://en.wikipedia.org/wiki/#{x.to_s}"
  article = open(url).read

  # saves current article to a file
  # (only possible with 1.9.x use open too if on 1.8.x)
  IO.write("my_copy_of-#{x.to_s}.html", article)

  # add current article to summary file
  open("numbers.html", "a") do |f|
    f.write(article)
  end
end
于 2012-02-12T21:50:43.200 に答える