只有一个图像多次上传

时间:2015-07-20 12:49:22

标签: ruby-on-rails-4.2 ruby-2.1 mechanize-ruby

我一直在使用mechanize gem从craigslist中抓取数据,我有一段代码可以将多个图像上传到craigslist,所有文件路径都是正确的,但只有单个图像上传了多次,原因是什么? 。

 unless pic_url_arry.blank?
        unless page.links_with(:text => 'Use classic image uploader').first.blank?
          page = page.links_with(:text => 'Use classic image uploader').first.click
        end
        puts "After classic image uploader"
        form = page.form_with(class: "add")
        # build full file path before setting like this => file = File.join( APP_ROOT, 'tmp', 'image.jpg')
        i = 0
        pic_url_arry = pic_url_arry.shuffle
        pic_url_arry.each do |p|
          form.file_uploads.first.file_name = p
          i+= 1
          page = form.submit
          puts "******#{p.inspect}*******"
          puts "******#{page.inspect}*******"
        end unless pic_url_arry.blank?
        # check if the file uploaded sucessfully with no. of files with no. of imgbox on page.
        check_image_uploaded = page.at('figure.imgbox').count
        if check_image_uploaded.to_i == i.to_i
          # upload failure craiglist or net error.
        end
      end  

并且pic数组的值为[" /home/codebajra/www/office/autocraig/public/uploads/posting_pic/pic/1/images__4_.jpg" ;," / home / codebajra / www / office / autocraig / public / uploads / posting_pic / pic / 2 / mona200.jpg"," / home / codebajra / www / office / autocraig / public / uploads / posting_pic / pic / 3 / images__1_.jpg&#34]。

1 个答案:

答案 0 :(得分:1)

表单保留文件字段仅设置一次,只拍摄一张首先出现的图像。因此,更新的代码将是,

unless pic_url_arry.blank?
    unless page.links_with(:text => 'Use classic image uploader').first.blank?
      page = page.links_with(:text => 'Use classic image uploader').first.click
    end
    puts "After classic image uploader"
    form = page.form_with(class: "add")
    # build full file path before setting like this => file = File.join( APP_ROOT, 'tmp', 'image.jpg')
    i = 0
    pic_url_arry = pic_url_arry.shuffle
    pic_url_arry.each do |p|
      form.file_uploads.first.file_name = p
      i+= 1
      page = form.submit
      form = page.form_with(class: "add")
      puts "******#{p.inspect}*******"
      puts "******#{page.inspect}*******"
    end unless pic_url_arry.blank?
    # check if the file uploaded sucessfully with no. of files with no. of imgbox on page.
    check_image_uploaded = page.at('figure.imgbox').count
    if check_image_uploaded.to_i == i.to_i
      # upload failure craiglist or net error.
    end
  end  

希望这能解决问题。