2016-05-11 5 views
1

私はRubyが新しく、HTMLコンテンツを解析し、必要に応じて更新する必要があります( 'body'タグに属性を追加する必要があります)。私は、次のコードNokogiriは、コンテンツを損なうことなくhtmlタグに属性を追加します。

def index 
    url = "/home/employee/index.html" 
    doc = Nokogiri::HTML::Document.parse(url) 
    doc.at_css("body").set_attribute("ng-init", "menu.inspired = 'true'") 
    File.open('/home/employee/index.txt','w') {|f| doc.write_html_to f} 
    @content=doc.to_html 
end 

ファイルに書き込まれた出力は、以下の

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body ng-init="menu.inspired = 'true'"><p>/home/employee/index.html</p></body></html> 

出力ファイルが追加された属性が含まれていますが、htmlファイルの内容を上書きしているように見えるで書かれています。だから私は間違いがどこにあるかを理解する必要があります。

答えて

1

/home/employee/index.htmlの代わりにNokogiri::HTML::Document.parse(url)は、本体が"/home/employee/index.html"のスケルトンHTML文書を作成します。

最初にファイルから文書を読む必要があります。

def index 
    # note that this is a file path! Not an URL. 
    path = "/home/employee/index.html" 
    doc = File.open(path) { |f| Nokogiri::HTML(f) } 
    doc.at_css("body").set_attribute("ng-init", "menu.inspired = 'true'") 
    File.open(path,'w') {|f| doc.write_html_to f} 
    @content=doc.to_html 
end 

参照してください:

関連する問題