ruby 从 google 获取随机图片

ruby get random pic from google

我正在寻找一些代码。我使用的是 ruby.

的最新版本

我正在开发一个用于 discord 的机器人,它可以在文本通道中发送随机图片。 例如: 机器人正在使用关键字 'sun' 搜索 google 图片。然后他应该从 1000000000000 的结果中随机拍一张并在 discord 中发送。

我搜索了一个 google api,我搜索了一个代码,但没有任何效果。 我想我在这里坐了大约 2 个小时,我尝试的每个代码都失败了。

所以是的,希望你能帮助我。

LG

irb 中尝试 运行 这个:

require 'nokogiri'
require 'open-uri'

puts "Type in a search term below:\n\n"

# get user search term
search_term = gets.chomp

# construct EN google image search results page
url = "https://www.google.com/search?q=#{search_term}&hl=en&tbm=isch"

# scrape google images
doc = Nokogiri::HTML.parse(open(url).read)

# store all image urls on the first search page in an array
imgs = doc.search('img').map(&:attributes).map { |node| node['src'].value }

# filter bad urls
imgs.select { |url| url.match(/https/) }

# print and return random image url
image = imgs[rand(0..imgs.length-1)]
p image

当然 Google 图片 API 会比抓取更好。如果您可以编辑您的评论并提供您的脚本代码和 Google API 返回的 JSON 结构,我们将更容易为您调试它。