【问题标题】:ruby get random pic from google [closed]红宝石从谷歌获得随机图片[关闭]
【发布时间】:2021-01-23 21:08:34
【问题描述】:
我正在寻找一些代码。我正在使用最新版本的 ruby。
我正在开发一个不和谐的机器人,它在文本通道中发送随机图片。
例如:
该机器人正在使用关键字“sun”搜索谷歌图片。然后他应该从 1000000000000 个结果中随机抽取一张照片,然后将其发送到 discord 中。
我已经搜索了一个 google api,我已经搜索了一个代码,但没有任何效果。
我想我在这里坐了 2 个小时,我尝试的每个代码都失败了。
是的,希望你能帮帮我。
LG
【问题讨论】:
标签:
ruby
api
rubygems
discord
bots
【解决方案1】:
尝试在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 结构,我们将更容易为您调试它。