Parse HTML and preserve original content

Viewed 2149

I have lots of HTML files. I want to replace some elements, keeping all the other content unchanged. For example, I would like to execute this jQuery expression (or some equivalent of it):

$('.header .title').text('my new content')

on the following HTML document:

<div class=header><span class=title>Foo</span></div>
<p>1<p>2
<table><tr><td>1</td></tr></table>

and have the following result:

<div class=header><span class=title>my new content</span></div>
<p>1<p>2
<table><tr><td>1</td></tr></table>

The problem is, all parsers I’ve tried (Nokogiri, BeautifulSoup, html5lib) serialize it to something like this:

<html>
  <head></head>
  <body>
    <div class=header><span class=title>my new content</span></div>
    <p>1</p><p>2</p>
    <table><tbody><tr><td>1</td></tr></tbody></table>
  </body>
</html>

E.g. they add:

  1. html, head and body elements
  2. closing p tags
  3. tbody

Is there a parser that satisfies my needs? It should work in either Node.js, Ruby or Python.

7 Answers
Related