红宝石从谷歌获取随机图片

时间:2020-10-08 18:54:14

标签: ruby api rubygems discord bots

我正在搜索一些代码。我正在使用最新版本的ruby。

我正在为一种不和谐的机器人而工作,该机器人在文本通道中发送随机图片。 例如: 机器人正在用关键字“ sun”搜索google图片。然后他应该从1000000000000个结果中随机抽取一张图片,然后将其发送到不一致的地方。

我正在搜索一个google api,我正在搜索一个使它成功的代码,但是没有任何效果。 我想我在这里坐了两个小时,而我尝试的每个代码都失败了。

是的,希望你能帮助我。

LG

1 个答案:

答案 0 :(得分:2)

尝试在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结构,那么我们将更容易为您调试它。