如何在ruby中设置自定义用户代理

rub*_*ter 19 ruby user-agent net-http

我的任务是通过自动化测试URL上的不同用户代理.我正在使用ruby进行编码,我一直在尝试使用以下方法设置用户代理,但它似乎无法识别用户代理.

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

有没有其他方法可以做到这一点,或者我做错了什么?

小智 26

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
Run Code Online (Sandbox Code Playgroud)

对我来说很棒.


小智 17

另一个对我有用的:

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

希望这会帮助你.