Ruby——httparty使用代理
环境配置:
- Ruby
- httparty
安装httparty库
gem install httparty
代码样例
使用代理
require "httparty" # 引入httparty模块 require 'zlib' require 'stringio' # 代理服务器ip和端口 proxy_ip = '47.115.5.19' proxy_port = 16816 # 要访问的目标网页, 以京东首页为例 page_url = 'https://dev.kuaidaili.com/testproxy' # 设置headers headers = { "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50", "Accept-Encoding" => "gzip", } # 设置代理 options = { :headers => headers, :http_proxyaddr => proxy_ip, :http_proxyport => proxy_port, } # 发起请求 res = HTTParty.get(page_url, options) # 输出状态码 puts "status code: #{res.code}" # 输出响应体 if res.code.to_i != 200 then puts "page content: #{res.body}" else gz = Zlib::GzipReader.new(StringIO.new(res.body.to_s)) puts "page content: #{gz.read}" end
运行下,看看结果。
进阶学习
相关推荐
PMJ0 2020-10-13
longzhiwen 2020-09-06
yangxingstar 2020-08-31
LUCIEN0 2020-08-17
huangzihao00 2020-08-17
Jan 2020-08-17
AndesStay 2020-06-12
afengxg 2020-06-09
zamesking 2020-06-09
afengxg 2020-06-09
何志文 2020-06-09
teresalxm 2020-06-05
何志文 2020-05-16
何志文 2020-05-11
fsl 2020-05-04
JOO 2020-04-26
倩 2020-04-22
afanti 2020-04-19
始终不够 2020-04-10