【问题标题】:Ruby - How can I follow a .php link through a request and get the redirect link?Ruby - 如何通过请求跟踪 .php 链接并获取重定向链接?
【发布时间】:2017-12-18 22:44:51
【问题描述】:

首先我想明确一点,我一点也不熟悉 Ruby。

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

但是,UD 没有官方 API,所以我使用的是this。这是一个用 Ruby 编写的 Heroku 应用程序。据我了解,它会为给定的搜索抓取 UD 页面。

我想将随机添加到我的 Bot,但 API 不支持它,我想添加它。

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

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

【问题讨论】:

    标签: ruby http heroku


    【解决方案1】:

    这是使用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 状态代码),因此“新” 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
    

    【讨论】:

    • 我认为“红宝石”方式可以避免像瘟疫一样的net/http
    • 我认为在 Go 中应该有相同的方式直接执行此操作。这将使您的项目更加一致(一种语言)并且更易于维护。
    • @MarkThomas 为什么会这样?
    • @StephanePaquet 我没有在 Go 中嵌入 Ruby,我想扩展 API 以便在 Go 中使用它。但实际上,Go 遵循重定向,我不知道如何获取我被重定向到的 URL,这个答案提供了一个线索
    • @Elegea 因为net/http 尽管在标准库中,但在 Ruby 社区中被认为具有过时且繁琐的 API。常见的替代方案是 rest-client、httpclient、API 的 HTTParty 和抓取的 Mechanize。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多