How to prevent Nokogiri from adding tags?

前端 未结 2 1209
-上瘾入骨i
-上瘾入骨i 2020-12-05 17:14

I noticed something strange using Nokogiri recently. All of the HTML I had been parsing had been given start and end and

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 18:05

    The problem occurs because you're using the wrong method in Nokogiri to parse your content.

    require 'nokogiri'
    
    doc = Nokogiri::HTML('

    foobar

    ') puts doc.to_html # >> # >>

    foobar

    Rather than using HTML which results in a complete document, use HTML.fragment, which tells Nokogiri you only want the fragment parsed:

    doc = Nokogiri::HTML.fragment('

    foobar

    ') puts doc.to_html # >>

    foobar

提交回复
热议问题