Nokogiri: how to find a div by id and see what text it contains?
Asked Answered
R

2

11

I just started using Nokogiri this morning and I'm wondering how to perform a simple task: I just need to search a webpage for a div like this:

<div id="verify" style="display:none"> site_verification_string </div>

I want my code to look something like this:

require 'nokogiri'
require 'open-uri'

url = h(@user.first_url)
doc = Nokogiri::HTML(open(url))
if #SEARCH_FOR_DIV#.text == site_verification_string
  @user.save
end

So the main question is, how do I search for that div using nokogiri?

Any help is appreciated.

Regenerate answered 22/7, 2012 at 16:40 Comment(0)
F
21
html = <<-HTML
  <html>
    <body>
      <div id="verify" style="display: none;">foobar</div>
    </body>
  </html>
HTML
doc = Nokogiri::HTML html
puts 'verified!' if doc.at_css('[id="verify"]').text.eql? 'foobar'
Fruitful answered 22/7, 2012 at 16:51 Comment(0)
T
8

For a simple way to get an element by its ID you can use .at_css("element#id")

Example for finding a div with the id "verify"

html = Nokogiri::HTML(open("http://example.com"))
puts html.at_css("div#verify")

This will get you the div and all the elements it contains

Tedi answered 19/1, 2017 at 4:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.