[英]How to GET a URL with User-Agent and timeout through some Proxy in Ruby?
如果我需要通过某个代理来获取URL,该URL必须具有最大为max n的超时 。 秒和一个User-Agent ?
require 'nokogiri'
require 'net/http'
require 'rexml/document'
def get_with_max_wait(param, proxy, timeout)
url = "http://example.com/?p=#{param}"
uri = URI.parse(url)
proxy_uri = URI.parse(proxy)
http = Net::HTTP.new(uri.host, 80, proxy_uri.host, proxy_uri.port)
http.open_timeout = timeout
http.read_timeout = timeout
response = http.get(url)
doc = Nokogiri.parse(response.body)
doc.css(".css .goes .here")[0].content.strip
end
上面的代码通过具有超时的代理获取URL,但是缺少User-Agent 。 如何使用 User-Agent获得它?
您应该使用open-uri并将用户代理设置为open function中的参数。
下面是一个示例,其中我在变量中设置用户代理并将其用作打开函数中的参数。
require 'rubygems'
require 'nokogiri'
require 'open-uri'
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.854.0 Safari/535.2"
url = "http://www.somedomain.com/somepage/"
@doc = Nokogiri::HTML(open(url, 'proxy' => 'http://(ip_address):(port)', 'User-Agent' => user_agent, 'read_timeout' => 10 ), nil, "UTF-8")
有一个选项可以在openURI中设置读取时间
您可以在以下链接中查看Open URI的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.