[英]Ruby Mechanize, Nokogiri and Net::HTTP
我正在使用Net :: HTTP進行HTTP請求並獲得響應:
uri = URI("http://www.example.com")
http = Net::HTTP.start(uri.host, uri.port, proxy_host, proxy_port)
request = Net::HTTP::Get.new uri.request_uri
response = http.request request # Net::HTTPResponse object
body = response.body
如果我必須使用Nokogiri gem來解析這個HTML響應,我會這樣做:
nokogiri_obj = Nokogiri::HTML(body)
但是如果我想使用Mechanize gem我需要這樣做:
agent = Mechanize.new
mechanize_obj = agent.get("http://www.example.com")
我是否可以使用Net :: Http獲取HTML響應,然后使用Mechanize gem將其轉換為Mechanize對象而不是使用agent.get()
?
編輯:
繞過agent.get()
方法的原因是因為我試圖使用EventMachine::Iterator
來發出並發的EM-HTTP
請求。
EventMachine.run do
EM::Iterator.new(urls, 3).each do |url,iter|
puts "giving #{url} to httprequest now"
http = EM::HttpRequest.new(url).get
http.callback { |resp|
uri = resp.send(:URI, url)
puts "inside callback of #{url}"
body = resp.response
page = agent.parse(uri, resp, body)
}
iter.next
end
end
但它不起作用。 我收到一個錯誤:
/usr/local/rvm/gems/ruby-1.9.3-p194/gems/mechanize-2.5.1/lib/mechanize.rb:1165:in`parse': undefined method `[]' for #<EventMachine::HttpClient:0x0000001c18eb30> (NoMethodError)
當我使用Net::HTTP
的parse
方法時,它工作正常,我得到了Mechanize對象:
uri = URI("http://www.example.com")
http = Net::HTTP.start(uri.host, uri.port, proxy_host, proxy_port)
request = Net::HTTP::Get.new uri.request_uri
response = http.request request # Net::HTTPResponse object
body = response.body
agent = Mechanize.new
page = agent.parse(uri, response, body)
我在使用em-http時是否為parse
方法傳遞了錯誤的參數?
我不確定你為什么認為使用Net :: HTTP會更好。 Mechanize將處理重定向和cookie,並提供對Nokogiri解析文檔的隨時訪問。
require 'mechanize'
agent = Mechanize.new
page = agent.get('http://www.example.com')
# Use Nokogiri to find the content of the <h1> tag...
puts page.at('h1').content # => "Example Domains"
注意,設置user_agent
不一定要到達example.com。
如果您想使用線程引擎來檢索頁面,請查看Typhoeous和Hydra 。
看起來Mechanize
有一個parse
方法 ,所以這可以工作:
mechanize_obj = Mechanize.parse(uri, response, body)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.