2012-03-03 2 views
12

일반적으로 Mechanize는 URL에서 웹 페이지를 가져오고 get 메소드의 결과는 많은 유용한 메소드를 사용할 수있는 Mechanize :: Page 객체입니다 .Ruby Mechanize가 문자열에있는 페이지를 가져 오는 방법

페이지가 문자열로되어있는 경우 동일한 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 = ... 

답변

19

기계화는 Nokogiri를 사용하여 HTML을 구문 분석합니다. 인터넷 전송 프로토콜을 사용하지 않고 HTML에 액세스하는 경우 Mechanize가 필요하지 않습니다. 입력 HTML을 구문 분석하는 것뿐입니다.

다음은이 작업을 수행하게됩니다 :

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

당신은 기계화 보석은 이미 노코 기리가됩니다 설치 한 경우.

그렇지 않으면 당신은 여전히 ​​사용하여 새 기계화 페이지를 만들 수 있습니다 :

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