2
votes

I want to test is whether the table element exists? And if there is no table then I just want the script to end. However if there is a table I want to output it to excel.

The script is testing two url's:

http://www.mycounciltax.org.uk/results?postcode=EX99AE&search=Search

http://www.mycounciltax.org.uk/results?postcode=CV56bz&search=Search

The first url presents a web page without a html table and the second presents a web page which includes a html table element.

I have tried putting the following script together but I don't think this is correct. I am sure I have made a mistake with testing the for the table element.

if browser.table.trs.collect {|tr| [tr[0].text, tr[1].text, tr[2].text]}.exists?
then content = browser.table.trs.collect {|tr| [tr[0].text, tr[1].text, tr[2].text]}

If you remove the above code from the below script it will run but will fall over when it doesn't find the html table.

require "watir-webdriver"
browser = Watir::Browser.new :ff
browser.goto "http://www.mycounciltax.org.uk/results?postcode=CV56BZ&search=Search"

if browser.table.trs.collect {|tr| [tr[0].text, tr[1].text, tr[2].text]}.exists?
then content = browser.table.trs.collect {|tr| [tr[0].text, tr[1].text, tr[2].text]}
require 'win32ole'

application = WIN32OLE.new('Excel.Application')

application.visible = TRUE
workbook = application.Workbooks.Add();
worksheet = workbook.Worksheets(1);
worksheet.visible

row = 1; column = 0
content.each do |array|
array.each do |element|
worksheet.Cells(1,1).offset(row,column).value = element #.offset(row,column)
column += 1
end
row += 1
column = 0
end

else end

browser.goto "http://www.mycounciltax.org.uk/results?postcode=EX99AE&search=Search"

if browser.table.trs.collect {|tr| [tr[0].text, tr[1].text, tr[2].text]}.exists?
then content = browser.table.trs.collect {|tr| [tr[0].text, tr[1].text, tr[2].text]}
require 'win32ole'

application = WIN32OLE.new('Excel.Application')

application.visible = TRUE
workbook = application.Workbooks.Add();
worksheet = workbook.Worksheets(1);
worksheet.visible

row = 1; column = 0
content.each do |array|
array.each do |element|
worksheet.Cells(1,1).offset(row,column).value = element #.offset(row,column)
column += 1
end
row += 1
column = 0
end

else end

I plan to run the above code at once. Can anyone point out where I am going wrong? I am new to ruby and watir :-).

Many thanks in advance.

2

2 Answers

5
votes

There is an #exists? method.

if browser.table.exists?
  # go on
end
0
votes

Flip your logic.

if browser.text.include? ("Sorry. We couldn't find any properties for the postcode")
   puts "no table here"
   #quit/close/move on to next test/etc
else
   #do some stuff
end

You can do it your way, but that collect method is a very fragile - if the table or anything above it every moves, the script will fail.

search_result = browser.table(:index, 0) #or :index, 1 for WATIR 1.X

if search_result.exists?
   #do some stuff
else
   puts "table not found"
end