2012-03-03 10 views
12

Generalmente Mechanize obtendrá una página web de una URL y el resultado del método get es un objeto Mechanize :: Page, del cual puede usar muchos métodos útiles .Cómo dejar que Ruby Mechanize obtenga una página que viva en una cadena

Si la página vive en una cadena, ¿cómo obtengo el mismo objeto Mechanize :: Page?

require 'mechanize' 

html = <<END_OF_STRING 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
<title>Page Title</title> 
<style type="text/css"> 
</style> 
</head> 
<body> 
<h1>This is a test</h1> 
</body> 
</html> 
END_OF_STRING 

agent = Mechanize.new 

# How can I get the page result from the string html? 
#page = ... 

Respuesta

19

Mechanize utiliza Nokogiri para analizar el código HTML. Si está accediendo al HTML sin la necesidad de un protocolo de transferencia de Internet, no necesita Mechanize. Todo lo que buscas hacer es analizar el HTML de entrada, ¿verdad?

Lo siguiente le permitirá hacer esto:

require 'Nokogiri' 
html = 'html here' 
page = Nokogiri::HTML html 

Si ha instalado la gema Mechanize ya tendrá Nokogiri.

De lo contrario todavía se puede crear una nueva página Mechanize usando:

require 'Mechanize' 
html = 'html here' 
a = Mechanize.new 
page2 = Mechanize::Page.new(nil,{'content-type'=>'text/html'},html,nil,a) 
Cuestiones relacionadas