Nokogiri将属性添加到html标记而不会损坏其内容

时间:2016-05-11 10:28:34

标签: ruby-on-rails nokogiri

我是ruby的新手,需要解析html内容并根据需要进行更新(将属性添加到' body'标记)。我写了以下代码

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 个答案:

答案 0 :(得分: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

请参阅: