简体   繁体   中英

How do I wrap HTML untagged text with <p> tag using Nokogiri?

I have to parse an HTML document into different new files. The problem is that there are text nodes which have not been wrapped with "<p>" tags, instead they having "<br>" tags at the end of each paragraph.

I want to wrap this text with <p> tags using Nokogiri:

<div id="f15"><b>Footnote 15</b>: Catullus iii, 12.</div>
<div class="pgmonospaced pgheader"><br/>
<br/>
End of the Project abc<br/>
<br/>
*** END OF THIS PROJECT XYZ ***<br/>
<br/>
***** This file should be named new file.html... *****<br/>
<br/></div>

After searching around some forums and doing some debugging locally, i have found the following solution to my problem.

html_doc = Nokogiri::HTML.parse('path/to/html_file')
html_doc
html_doc.search("//br/preceding-sibling::text()|//br/following-sibling::text()").each do |node|
    node.replace(Nokogiri.make("<p>#{node.to_html}</p>"))
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM