ironsand
ironsand

Reputation: 15161

How to reject specify HTML tags by using css or xpath selector

I want to remove style and script tags and the contents of them by using css or xpath selector.

This is a example HTML:

<html>
  <head>
    <title>test</title>
    <style>
      // style
    </style>
    <script>
      /* some script */
    </script>
  </head>
  <body>
    <p>text</p>
    <script>
      /* some script */
    </script>
    <div>foo</div>
  </body>
</html>

I want to get a HTML like this:

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>text</p>
    <div>foo</div>
  </body>
</html>

I thought I can get HTML that doesn't including <script> tags with this code, but somehow the code only duplicate the HTML.

doc = Nokogiri::HTML(open("foo.text"))
doc.css(":not(script)").to_html

How can I enable the behavior I want?

Upvotes: 1

Views: 259

Answers (2)

pguardiario
pguardiario

Reputation: 54984

Simpler is just:

doc.search('style,script').remove

Upvotes: 1

Mourad
Mourad

Reputation: 474

Try these lines:

doc.search('.//style').remove
doc.search('.//script').remove

Upvotes: 1

Related Questions