You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
require'nokogiri'# remote sourcesource=open('url')doc= ::Nokogiri.new# HTML snippet (without html and body)doc= ::Nokogiri::HTML::fragment('<div>content</div>','UTF-8')# XMLdoc= ::Nokogiri::XML('<?xml version="1.0" encoding="utf-8"?></xml>')
Find Elements
links=doc.css('a')link=doc.at_css('a')# same as doc.css('a').first
Get Element Info
doc=Nokogiri::HTML::fragment('<a href="example.com" id="a" class="b"> <span>content</span> </a>')link=doc.at_css('a')# get attributeslink.attribute('id')# => 'a'link.attribute('class')# => 'b'link.attribute('href')# => 'example.com'# get all attributes link.attribute_nodes# get tag namelink.name# => 'a'# Get link content as textlink.text# => 'content'# get HTMLlink.inner_html# => '<span>content</span>'link.to_html# => '<a href="example.com" id="a" class="b"><span>content</span></a>'# get path to this element as CSS expressionlink.css_path
# create new elementel= ::Nokogiri::XML::Node.new('div')el.attr['id']='some-id'el.inner_html='<p>content</p>'el.# => '<div><p>content</p></div>'# adds #some-id after element #onedoc.css('#one').after(el)doc.css('#one').add_next_sibling(el)# adds #some-id before element #onedoc.css('#one').before(el)doc.css('#one').add_previous_sibling(el)# adds #some-id as #one childdoc.css('#one').add_child(el)# Replace #one with #some-iddoc.css('#one').replace(el)doc.css('#one').swap(el)# same as .replace, but returns self to support chaining
Remove Elements
doc.css('a').each{ |a| a.remove}# remove all links