我正在尝试理解链接预览是如何工作的(例如,在Facebook或Reddit这样的网站上,当发布链接时,文章的图像和标题是预览的):如何在不知道文章的确切图像url的情况下获得文章的主图像?
例如,在这个site上,我的链接预览器应该向我显示这个image (“主”图像),而不是例如this one (它是一个更下面的图像)。
我是一个ruby新手,但是我能够使用Nokogiri和Open-Uri获得所有的图像,并使用下面的代码(但是问题仍然存在:我如何只获得主图像?):
URL = "https://www.theguardian.com/technology/2016/dec/12/facebook-2016-problems-fake-news-censorship"
require 'open-uri'
require 'nokogiri'
Nokogiri::HTML(open(URL)).xpath("//img/@src").each do |src|
uri = URI.join( URL, src ).to_s
File.open(File.basename(uri), 'wb') do |f|
f.write(open(uri).read)
end
end发布于 2016-12-13 03:51:17
这是您的代码的一个稍微修改的版本。对于提供的链接,它工作得很好,你必须调整它以适应其他网站。
它使用w=后跟一个大于300的数字来解析图像URL的代码。
它下载第一个找到的图像,可能具有更高的分辨率(desired_width = 800)
URL = 'https://www.theguardian.com/technology/2016/dec/12/facebook-2016-problems-fake-news-censorship'.freeze
require 'open-uri'
require 'nokogiri'
minimum_width = 300
desired_width = 800
width_regex = /(w=)(\d+)/
Nokogiri::HTML(open(URL)).xpath('//img/@src').find do |src|
basename = File.basename(src)
next unless basename =~ width_regex &&
Regexp.last_match(2).to_i >= minimum_width
without_parameters = basename.split('?').first
puts "Found #{without_parameters} !"
uri = URI.join(URL, src.to_s.sub(width_regex, '\1' + desired_width.to_s))
File.open(without_parameters, 'wb') do |f|
f.write(open(uri).read)
end
end对于给定的示例:
Found 2330.jpg !https://stackoverflow.com/questions/41104917
复制相似问题