watir - ruby code "undefined method present? pr exist" - ruby

require 'rubygems'
require "watir"
browser = Watir::Browser.new :chrome,:switches => %w[--disable-notifications]
i=0;
begin
#TODO logining to the facebook
browser.goto 'linkedin.com'
browser.text_field(:id => 'login-email').set 'ananthragavendra#gmail.com'
browser.text_field(:id => 'login-password').set 'ru09ec32'
browser.button(type: 'submit').click
puts '**** linkedin logged in ****'
sea = browser.div(:class => 'nav-search-bar')
puts sea
if sea.exits?
browser.div(:class => 'nav-search-bar').click
browser.div(:class => 'type-ahead-input-container').text_field.set 'wipro'
browser.button(:class => 'nav-search-button').click
puts '**** searched, the results for wipro is shown '
else
puts 'div not present'
end
side = browser.div(:class => 'right-rail search-right-rail')
puts side
if side.present?
puts 'div present'
side1 = browser.divs(:class => 'right-rail search-right-rail')
else
puts 'div not present'
end
#TODO exception handling
rescue Exception => e
p "Error Found..... #{e.message}"
end
The error is thrown while executing the above simply, I am able to found the div in real time but I am unable to check the div using if commands, I have also tried some codes like exists.

First of all, this line if sea.exits? is wrong, change this to if sea.exists?
And your code is perfect, but very minute changes require to effectuate the WATIR's predefined wait statement.
You used this statement
side = browser.div(:class => 'right-rail search-right-rail')
If you write this way, then WATIR's predefined wait doesn't work because the method which you are going to call upon Watir::Div object is where four checking happens,
for an example, if you call
browser.div(:class => 'right-rail search-right-rail').click
then these four following checking will happen
1)exist?
2)enabled?
3)present?
4)writable?
But if you don't call any function as I have shown then it will NOT return the element because statement is getting executed even before element is loaded, So as a result of that side.present? is false and it gives you the result that div not present
So change your code in the following way
browser.div(:class => 'right-rail search-right-rail').click
side = browser.div(:class => 'right-rail search-right-rail')
puts side
if side.present?
puts 'div present'
side1 = browser.divs(:class => 'right-rail search-right-rail')
else
puts 'div not present'
end
Now your code will work perfectly. present method will return true for you.

present? is added to Object by Rails. So if you are outside of Rails, you probably mean: !side.nil?

Related

Capture the response from watir-webdriver

Is there a way to capture the entire response from a query submitted via a watir-webdriver object/request. For example if I took the sample code below, is there an element that will capture the entire page from the form submission so that I may parse it for errors?
#!/usr/bin/ruby
require 'watir-webdriver'
b = Watir::Browser.new
b.goto 'bit.ly/watir-webdriver-demo'
b.text_field(:id => 'entry_0').set 'your name'
b.select_list(:id => 'entry_1').select 'Ruby'
b.select_list(:id => 'entry_1').selected? 'Ruby'
b.button(:name => 'submit').click
b.text.include? 'Thank you'
The .html element will return the page's source.
puts b.html will return the source of the current page.

Ruby rescue syntax error

I have the following line of code that is giving me an error:
rescue Timeout::Error => e
logs.puts("Rescued a timeout error...#{e}")
email_ids_all.each do |email_delete|
call= "/api/v2/emails/#{email_delete}/"
uri= HTTParty.delete("https://www.surveys.com#{call}",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/x-www-form-urlencoded', 'Content-Length' => "0" }
)
puts "Deleted email #{email_delete}".green
log.puts("Deleted email #{email_delete}")
end
abort #abort entire script after deleting emails
end
The error I am receiving is this:
syntax error, unexpected keyword_rescue, expecting $end
rescue Timeout::Error => e
^
Essentially I am just trying to run an API delete call if the script times out. It doesn't seem to matter what I put in the block for rescue though, I receive the same error. What's wrong with my syntax on the rescue method?
The format for using rescue is as follows:
begin
# Code you want to run that might raise exceptions
rescue YourExceptionClass => e
# Code that runs in the case of YourExceptionClass
rescue ADifferentError => e
# Code that runs in the case of ADifferentError
else
# Code that runs if there was no error
ensure
# Code that always runs at the end regardless of whether or not there was an error
end
Here is a question with lots more information: Begin, Rescue and Ensure in Ruby?.

checking if a html element is true with ruby and watir?

at the moment I have this:
def burnChart()
#browser.div(:id => "container").div(:id => "header").img(:class => "cogMenuHover").click
#browser.div(:id => "container").div(:id => "header").div(:class => "sbTopMenu").li(:class => "taskMenuOp", :index =>1).click
if
assert(#browser.send(type.to_sym, :class, "highcharts-grid").exists?)
puts 'Chart has been found!'
else
puts 'No chart was generated'
end
end
originally I thought I had to use to_css? but from what I've seen of others using it, that's incorrect I'm unsure.
Can anyone help me out, I just want to check if a class exists and return a true or fasle to log an error or a confirmation
I believe you want:
def burnChart()
#browser.div(:id => "container").div(:id => "header").img(:class => "cogMenuHover").click
#browser.div(:id => "container").div(:id => "header").div(:class => "sbTopMenu").li(:class => "taskMenuOp", :index =>1).click
#Due to using IE, it looks like .exists? has to be used.
if #browser.element(:class, "highcharts-grid").exists?
puts 'Chart has been found!'
else
puts 'No chart was generated'
end
end
Notice that:
The check for the element should be the condition for the if statement.
Changed the check to be .present?. .exists? returns true as long as the element is on the page, but usually you also want to check that it is visible.
The switch to #browser.element instead of #browser.send. You can do what you were doing, but you were not defining a type anywhere, so seemed unnecessary.

Alert box in Waitr Webdriver

I had a look here: http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups
Every solution is for IE on Windows. I am using Firefox on Mac. Is there a way to click on OK of a JavaScript alert box?
Proper handling of alerts and prompts is still being worked on in WebDriver, but a common workaround is to overwrite the window functions using execute_script(), i.e.
browser.execute_script("window.alert = function(msg) { window.lastAlert = msg; }")
browser.button(:id => "trigger-alert").click
browser.execute_script("return window.lastAlert") #=> "the message"
Since I'd like to avoid a bunch of monkey patches floating around (a common problem in the Watir community), I've added some helper methods as an optional require - after the next release you should be able to do:
require "watir-webdriver/extensions/alerts"
browser.alert do
browser.button(:id => "alert").click
end #=> "the alert message"
browser.confirm(true) do
browser.button(:id => "confirm").click
end #=> "the confirm message"
browser.prompt("returned value") do
browser.button(:id => "prompt").click
end #=> { :message => "foo", :default => "bar" }
Note that this is temporary and the API may be removed in the future when the issue is resolved in WebDriver.
UPDATE:
Proper alert handling is now implemented. The above example would now be done like this:
browser.button(:id => "alert").click
browser.alert.ok
browser.button(:id => "confirm").click
browser.alert.ok # or browser.alert.close
browser.button(:id => "prompt").click
alert = browser.alert
alert.text #=> "foo"
alert.ok

mechanize html scraping problem

so i am trying to extract the email of my website using ruby mechanize and hpricot.
what i a trying to do its loop on all the page of my administration side and parse the pages with hpricot.so far so good. Then I get:
Exception `Net::HTTPBadResponse' at /usr/lib/ruby/1.8/net/http.rb:2022 - wrong status line: *SOME HTML CODE HERE*
when it parse a bunch of page , its starts with a timeout and then print the html code of the page.
cant understand why? how can i debug that?
its seems like mechanize can get more than 10 page on a row ?? is it possible??
thanks
require 'logger'
require 'rubygems'
require 'mechanize'
require 'hpricot'
require 'open-uri'
class Harvester
def initialize(page)
#page=page
#agent = WWW::Mechanize.new{|a| a.log = Logger.new("logs.log") }
#agent.keep_alive=false
#agent.read_timeout=15
end
def login
f = #agent.get( "http://****.com/admin/index.asp") .forms.first
f.set_fields(:username => "user", :password =>"pass")
f.submit
end
def harvest(s)
pageNumber=1
##agent.read_timeout =
s.upto(#page) do |pagenb|
puts "*************************** page= #{pagenb}/#{#page}***************************************"
begin
#time=Time.now
#search=#agent.get( "http://****.com/admin/members.asp?action=search&term=&state_id=&r=500&p=#{page}")
extract(pagenb)
rescue => e
puts "unknown #{e.to_s}"
#puts "url:http://****.com/admin/members.asp?action=search&term=&state_id=&r=500&p=#{page}"
#sleep(2)
extract(pagenb)
rescue Net::HTTPBadResponse => e
puts "net exception"+ e.to_s
rescue WWW::Mechanize::ResponseCodeError => ex
puts "mechanize error: "+ex.response_code
rescue Timeout::Error => e
puts "timeout: "+e.to_s
end
end
end
def extract(page)
#puts search.body
search=#agent.get( "http://***.com/admin/members.asp?action=search&term=&state_id=&r=500&p=#{page}")
doc = Hpricot(search.body)
#remove titles
#~ doc.search("/html/body/div/table[2]/tr/td[2]/table[3]/tr[1]").remove
(doc/"/html/body/div/table[2]/tr/td[2]/table[3]//tr").each do |tr|
#delete the phone number from the html
temp = tr.search("/td[2]").inner_html
index = temp.index('<')
email = temp[0..index-1]
puts email
f=File.open("./emails", 'a')
f.puts(email)
f.close
end
end
end
puts "starting extacting emails ... "
start =ARGV[0].to_i
h=Harvester.new(186)
h.login
h.harvest(start)
Mechanize puts full content of a page into history, this may cause problems when browsing through many pages. To limit the size of history, try
#mech = WWW::Mechanize.new do |agent|
agent.history.max_size = 1
end

Resources