保存网站中的所有图像文件 [英] Save all image files from a website

查看:58
本文介绍了保存网站中的所有图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为自己创建一个小应用程序,在其中运行 Ruby 脚本并保存我博客中的所有图像.

I'm creating a small app for myself where I run a Ruby script and save all of the images off of my blog.

在识别图像文件后,我不知道如何保存它们.任何帮助将不胜感激.

I can't figure out how to save the image files after I've identified them. Any help would be much appreciated.

require 'rubygems'
require 'nokogiri'
require 'open-uri'

url = '[my blog url]'
doc = Nokogiri::HTML(open(url))

doc.css("img").each do |item|
  #something
end

推荐答案

URL = '[my blog url]'

require 'nokogiri' # gem install nokogiri
require 'open-uri' # already part of your ruby install

Nokogiri::HTML(open(URL)).xpath("//img/@src").each do |src|
  uri = URI.join( URL, src ).to_s # make absolute uri
  File.open(File.basename(uri),'wb'){ |f| f.write(open(uri).read) }
end

使用代码从这里转换为绝对路径:使用Nokogiri提取链接时如何获取绝对URL?

Using the code to convert to absolute paths from here: How can I get the absolute URL when extracting links using Nokogiri?

这篇关于保存网站中的所有图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆