如何使用User-Agent获取URL并通过Ruby中的某个代理超时?

如果我需要通过某个代理获取URL,如何获取URL,它必须具有max n的超时 。 秒和用户代理

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函数中的参数。

下面是我在变量中设置用户代理并将其用作open函数中的参数的示例。

  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中设置readtime

您可以在下面的链接中查看Open URI的文档

打开URI文档