Ruby 中的图像抓取

发布于 2024-12-28 01:23:55 字数 100 浏览 3 评论 0原文

如何使用 Nokogiri 抓取特定 URL 上存在的图像?如果有比 Nokogiri 更好的选择,请提出建议。 css图像标签是.profilePic img

How do I scrape an image present on a particular URL using Nokogiri? If there are better options than Nokogiri please suggest. The css image tag is .profilePic img

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ヤ经典坏疍 2025-01-04 01:23:56

如果它只是一个带有 URL 的

PAGE = "http://site.com/page.html"
require 'nokogiri'
require 'open-uri'
html = Nokogiri.HTML(open(PAGE))
src  = html.at('.profilePic img')['src']
File.open("foo.png", "wb") do |f|
  f.write(open(src).read)
end

如果您需要将相对图像路径转换为绝对路径,请参阅:
https://stackoverflow.com/a/4864170/405017

If it is just an <img> with a URL:

PAGE = "http://site.com/page.html"
require 'nokogiri'
require 'open-uri'
html = Nokogiri.HTML(open(PAGE))
src  = html.at('.profilePic img')['src']
File.open("foo.png", "wb") do |f|
  f.write(open(src).read)
end

If you need to turn a relative image path into an absolute, see:
https://stackoverflow.com/a/4864170/405017

子栖 2025-01-04 01:23:56

懒惰的方法是使用 mechanize,因为它会为你计算出 url 和文件名:

require 'mechanize'
agent = Mechanize.new
doc = agent.get(url)
agent.get(doc.parser.at('.profilePic img')['src']).save

The lazy way is to use mechanize as it will figure out the urls and filenames for you:

require 'mechanize'
agent = Mechanize.new
doc = agent.get(url)
agent.get(doc.parser.at('.profilePic img')['src']).save
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文