开发者

How do I exclude a nested element when grabbing content using Nokogiri?

开发者 https://www.devze.com 2023-03-20 01:19 出处:网络
I have a page with content that looks similar to this: <div id=\"level1\"> <div id=\"level2\">

I have a page with content that looks similar to this:

<div id="level1">
    <div id="level2">
        <div id="level3">Crap i dont care about</div>
        Here is some text i want
        <br />
        Here is some more text i want
        <br />
        Oh i want this text too :)
    </div>
</div>

My goal is to capture the text in #level2 but the #level3 <div> is nested inside of it at the same level as the text I want.

Is it possible to some how exclu开发者_如何学Pythonde that <div>? Should I be modifying the document and simply removing the element before parsing?


require 'nokogiri'

xml = <<-XML
<div id="level1">
    <div id="level2">
        <div id="level3">Crap i dont care about</div>
        Here is some text i want
        <br />
        Here is some more text i want
        <br />
        Oh i want this text too :)
    </div>
</div>
XML

page = Nokogiri::XML(xml)
p page.xpath("//*[@id='level3']").remove.xpath("//*[@id='level2']").inner_text
# => "\n        \n        Here is some text i want\n        \n        Here is some more text i want\n        \n        Oh i want this text too :)\n    "

Now, you may clean the output text if you wish.


If your HTML fragment is in html, then you could do something like this:

doc = Nokogiri::HTML(html)
div = doc.at_css('#level2')   # Extract <div id="level2">
div.at_css('#level3').remove  # Remove <div id="level3">
text_you_want = div.inner_text

You could also do it with XPath but I find CSS selectors a bit simpler for simple cases like this.

0

精彩评论

暂无评论...
验证码 换一张
取 消