How to check text inside a <div>?

I am trying to access some text that is in a DIV.
I need to check if the page contains text so that I can return true or false.
The code I'm using is below:

cancel = browser.text.include?("Current Cancelled")
if cancel == true
puts "Line item cancelled"
else
puts "****Line item not cancelled****"
end

But it returns false every time.
Here is the code snippet of what I'm looking at:

enter image description here

+3
source share
6 answers

The likely reason this doesn't work is because the line you are testing contains a newline and non-decaying space.

It might work ...

if browser.div(:text, /Current.*Cancelled/).exists?
  puts "Line item cancelled"
else
  puts "****Line item not cancelled****"
end

or

if browser.text =~ /Current.*Cancelled/
  puts "Line item cancelled"
else
  puts "****Line item not cancelled****"
end

and etc.

+4
source

I would recommend using Nokogiri for content analysis.

require 'nokogiri'

doc = Nokogiri::HTML('<div><span class="label">Current</span>Cancelled</div>')
doc.at('//div/span[@class="label"]/../text()').text # => "Cancelled"

(doc.at('//div/span[@class="label"]/../text()').text.downcase == 'cancelled') # => true
!!(doc.at('//div/span[@class="label"]/../text()').text.downcase['cancelled']) # => true

- /.

+4

Watir #elements_by_xpath... . Watir API

DIV #text. , , .

AFIK Watir ( , Watir ).

+1

, , .

:

cancel = browser.table(:class, 'basic-table').each { |row|
  test = row.text.include?("Current Cancelled")
  return test if test == true
}
+1

. . , .

, :

div = browser.table(:class, 'basic-table').div(:text, /Cancelled/)

cancel = div.exist? and div.span(:index, 1).text == 'Current'
if cancel
   puts "Line item cancelled"
else
   puts "****Line item not cancelled****"
end
+1

You can also combine several approaches to the regular expression below (mainly from Kinofrost), with the idea of ​​narrowing it down to looking only inside one cell inside the table. This should be faster and less prone to false warning if the words "Current" and "Canceled" occur in this order with anything in between, elsewhere on the page.

if browser.table(:class, 'basic-table').cell(:text, /Current.*Cancelled/).exists?
   puts "Line item cancelled"
else
   puts "****Line item not cancelled****"
end
+1
source

All Articles