簡體   English   中英

Ruby - 如何通過請求跟蹤 a.php 鏈接並獲取重定向鏈接?

[英]Ruby - How can I follow a .php link through a request and get the redirect link?

首先,我想澄清一下,我根本不熟悉 Ruby。

我正在用 Go 構建一個 Discord Bot 作為練習,該機器人獲取 UrbanDictionary 定義並將它們發送給在 Discord 中詢問的任何人。

但是,UD 沒有官方 API,所以我使用是 . 這是一個用 Ruby 編寫的 Heroku 應用程序。 據我了解,它會為給定的搜索抓取 UD 頁面。

我想向我的 Bot 添加隨機數,但 API 不支持它,我想添加它。

正如我所見,這並不難,因為http://www.urbandictionary.com/random.php只會將您重定向到網站的正常鏈接。 這樣,如果我可以點擊鏈接到“正常”鏈接,獲取鏈接並將其傳遞到構建的抓取工具上,它可以像任何其他鏈接一樣返回。

我不知道如何遵循它,我希望我能得到一些指示、樣本或其他任何東西。

這是使用net/httpuri的“ruby”方式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM