require 'nokogiri'
require 'pp'
doc = Nokogiri::HTML::Document.parse(<<-eohtml)
"abc xyz<img src="abc"/> 123 <img src="abc"/><img src="xyz"/>"
eohtml
doc.css("img").each{|i| i.previous = '<br/>'}
puts doc.to_html
输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>"abc xyz<br><img src="abc"> 123 <br><img src="abc"><br><img src="xyz">"
</p></body></html>
根据OP的最新编辑:
require 'nokogiri'
require 'pp'
doc = Nokogiri::HTML::Document.parse(<<-eohtml)
"abc xyz<img src="abc"/> 123 <img src="abc"/><img src="xyz"/>"
eohtml
doc.css("img[src = abc]")[1].previous = "<br/>"
puts doc.to_html
输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>"abc xyz<img src="abc"> 123 <br><img src="abc"><img src="xyz">"
</p></body></html>