我的任务是通过自动化测试URL上的不同用户代理。我正在使用ruby进行编码,我一直在尝试使用以下方法设置用户代理,但它似乎无法识别用户代理。
@http = Net::HTTP.new(URL)
response = @http.request_get(URL, {'User-Agent' => useragent})
有没有其他方法可以做到这一点,或者我做错了什么?
答案 0 :(得分:25)
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
非常适合我。
答案 1 :(得分:17)
另一个对我有用的工作:
require 'open-uri'
html = open('http://your.site.com/the/page.html', 'User-Agent' => 'Ruby').read
puts html
希望这会对你有所帮助。
答案 2 :(得分:2)
包含的Net::HTTPHeader包含initialize_http_header方法:
@http = Net::HTTP.new(URL)
@http.initialize_http_header({'User-Agent' => useragent})
response = @http.request_get(URL)
HTH
答案 3 :(得分:1)
我无法找到适用于 https
和提供标头的解决方案。这是一个有效的版本:
require "net/http"
uri = URI("https://pokemongolive.com/events/community-day/")
request = Net::HTTP::Get.new(uri)
request["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => (uri.scheme == 'https')) {|http|
http.request(request)
}
puts response.code
puts response.body
使用的 Ruby 版本是:ruby 2.6.3p62 (2019-04-16 revision 67580)