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

I just started using Nokogiri this morning, and I am wondering how to accomplish a simple task: I just need to find the web page for the div as follows:

<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 look for this div using nokogiri?

Any help is appreciated.

+6
source share
2 answers
 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' 
+12
source

For an easy way to get an element by its identifier, you can use .at_css("element#id")

Example to search for div with identifier "verify"

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

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

+2
source

Source: https://habr.com/ru/post/921077/


All Articles