Nokogiri Summary
내 맘대로 nokogiri tutorial 초 간단 summary
쓰다보니 engineyard 블로그에 올라온게 더 간단하고 좋다
Parsing
쓰다보니 engineyard 블로그에 올라온게 더 간단하고 좋다
Parsing
- f = File.open("blossom.xml")
doc = Nokogiri::XML(f) { do |config|
config.strict.noent
end }
f.close - require 'open-uri'
doc = Nokogiri::HTML(open("...")) - parse(string 혹은 io, url=nil, encoding=nil, options=ParseOption, &block)
Searching
- xpath("//dramas//character")
- css("sitcoms name")
- 첫번째 항목을 쓰는 경우 xpath.first 대신 at_xpath, at_css 사용
- namespace 사용하는 경우
xpath("//car:tire", "car"=>"http://..."), css('car|tire')와 같이 지정
Modifying
- text 바꿀때는 content에 지정
h1 = @doc.at_css "h1"
h1.content = "Changed content..." - node 순서 바꿀때는 parent를 새로 지정하거나 add_next_sibling 메소드
- h1.name = "h2" <h1> -> <h2>
- h1['class'] = "show-title"
- 새 노드 추가
h3 = Nokogiri::XML::Node.new "h3", @doc
h3.content = "1977-1984"
h1.add_next_sibling(h3) - wrap 메소드로 nodeset에 html을 둘러쌀 수 있다
nodes = @doc.css "h1, div"
wrapper = nodes.wrap("
간단한 예제
댓글