2011-04-27 97 views
15

我有一項任務是通過自動化測試URL上的不同用戶代理。我使用ruby進行編碼,並且我一直在嘗試使用以下方法設置用戶代理,但似乎無法識別用戶代理。如何在ruby中設置自定義用戶代理

@http = Net::HTTP.new(URL) 
response = @http.request_get(URL, {'User-Agent' => useragent}) 

有沒有其他方法可以做到這一點,或者我做錯了什麼?

回答

21
http = Net::HTTP.new("your.site.com", 80) 
req = Net::HTTP::Get.new("/path/to/the/page.html", {'User-Agent' => 'your_agent'}) 
response = http.request(req) 
puts response.body 

對我很好用。

+0

真棒!!謝謝..這完美的作品! – rubytester 2011-04-27 21:37:43

+0

有沒有辦法在全局範圍內設置它,所以你不必在每次調用時都設置哈希值? – g33kz0r 2014-04-24 17:34:25

15

也是另一個是爲我工作:

require 'open-uri' 
html = open('http://your.site.com/the/page.html', 'User-Agent' => 'Ruby').read 
puts html 

希望這會幫助你。

2

附帶Net::HTTPHeader具有initialize_http_header方法:

@http = Net::HTTP.new(URL) 
@http.initialize_http_header({'User-Agent' => useragent}) 
response = @http.request_get(URL) 

HTH

+0

你在錯誤的班上打電話給你。不管用。 – user2398029 2016-01-14 21:16:23

+1

@ user2398029這是1.9.3。歡迎編輯:) – 2016-01-16 17:46:43

相關問題