Ruby - 如何通过请求关注.php链接并获取重定向链接?

时间:2017-07-14 00:07:32

标签: ruby http heroku

首先,我想明确表示我根本不熟悉Ruby。

我在Go中构建一个Discord Bot作为练习,机器人获取UrbanDictionary定义并将它们发送给Discord中的任何人。

但是,UD没有官方API,所以我使用this。它是用Ruby编写的Heroku应用程序。根据我的理解,它会刮擦给定搜索的UD页面。

我想在我的Bot中添加随机数,但API不支持它,我想添加它。

正如我所看到的,它并不难,因为http://www.urbandictionary.com/random.php只会将您重定向到网站的正常链接。这样,如果我可以按照指示"正常"一,获取链接并将其传递给构建的scrapper,它可以像任何其他链接一样返回。

我不知道如何遵循它,我希望我能得到一些指示,样品或任何东西。

1 个答案:

答案 0 :(得分:2)

这里是" ruby​​"使用net/httpuri

的方式
require 'net/http'
require 'uri'

uri = URI('http://www.urbandictionary.com/random.php')
response = Net::HTTP.get_response(uri)

response['Location']
# => "http://www.urbandictionary.com/define.php?term=water+bong"

Urban Dictionary正在使用HTTP重定向(在这种情况下为302状态代码),因此" new" URL将作为http标头(Location)传回。为了更好地了解上述操作,以下是使用curl和系统调用的方法

`curl -I 'http://www.urbandictionary.com/random.php'`. # Get the headers using curl -I
  split("\r\n"). # Split on line breaks
  find{|header| header =~ /^Location/}. # Get the 'Location' header
  split(' '). # Split on spaces
  last # Get the last element in the split array
相关问题