Save image with Mechanize and Nokogiri?

后端 未结 1 1114
感情败类
感情败类 2021-01-02 18:59

I\'m using Mechanize and Nokogiri to gather some data. I need to save a picture that\'s randomly generated at each request.

In my attempt I\'m forced to download all

相关标签:
1条回答
  • 2021-01-02 19:49

    To fetch the images from the specific location:

    agent = Mechanize.new
    page = agent.get('http://www.domain.com')
    images = page.search("#specific img")
    

    To save the image:

    agent.get(images.first.attributes["src"]).save "path/to/folder/image_name.jpg"
    

    To get image encoded without saving:

    encoded_image = Base64.encode64 agent.get(images.first.attributes["src"]).body_io.string
    

    I ran this just to make sure that the image that was encoded can be decoded back:

    File.open("images/image_name.jpg", "wb") {|f| f.write(Base64.decode64(encoded_image))}
    
    0 讨论(0)
提交回复
热议问题