Selenium-Webdriver Ruby --> How to wait for images to be fully loaded after click - ruby

I am very new to Ruby and Selenium-Webdriver, so please, help :)
I am trying to open email campaign , sent to my inbox, that has images and take a screenshot in the firefox. But i can not make it wait until images is fully loaded. Once i click on 'Show images' , screenshot is already taken , but image is not loaded at that time. How can i pause the script and take screenshot some time later, after all images is displayed?
Please, help :(
Bellow is my script:
enter code here
require 'selenium-webdriver'
browser = Selenium::WebDriver.for :firefox
#==========================================================================================
wait = browser.manage.timeouts.implicit_wait = 15
#==========================================================================================
url = 'https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym'
# Open browser (firefox)
browser.navigate.to url
browser.find_element(:id, 'username').send_keys "some yahoo id"
browser.find_element(:id, 'passwd').send_key "some password"
browser.find_element(:id, ".save").click
browser.find_element(:id, "inbox-label").click
browser.find_element(:xpath, "//div[#class='subj']").click
browser.find_element(:xpath, "//a[#title='Display blocked images']").click
result_page_title = browser.find_element(:tag_name, 'title')
puts "Title of the page: \t\t: #{result_page_title.text}"
browser.save_screenshot "1.jpg"

You can use Implicit Wait and Explicit Wait to wait for a particular Web Element until it appears in the page. The wait period you can define and that is depends upon the application.
Explicit Wait:
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. If the condition achieved it will terminate the wait and proceed the further steps.
Code:
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(strEdit)));
Or
WebElement myDynamicElement = (new WebDriverWait(driver, 30))
.until(new ExpectedCondition<WebElement>(){
#Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});
This waits up to 30 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 30 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.
You can use ExpectedConditions class as you need for the application.
Implicit Wait:
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available
Code:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
One thing to keep in mind is that once the implicit wait is set - it will remain for the life of the WebDriver object instance
For more info use this link http://seleniumhq.org/docs/04_webdriver_advanced.jsp
The above code is in Java. Change as your language need.

Ruby code from the docs (click on the 'ruby' button):
wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds
begin
element = wait.until { driver.find_element(:id => "some-dynamic-element") }
ensure
driver.quit
end
Which works for me

To add to the above answer, here is how I use implicit and explicit wait in Ruby.
Implicit Wait
I pass this option to Selenium::WebDriver after initializing with a couple of lines like this:
browser = Selenium::WebDriver.for :firefox
browser.manage.timeouts.implicit_wait = 10
Just replace "10" with the number of seconds you'd like the browser to wait for page refreshes and other such events.
Explicit Wait
There are two steps to declaring an explicit wait in Selenium. First you set the timeout period by declaring a wait object, and then you invoke the wait with Selenium::Webdriver's .until method. It would look something like this, in your example:
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { browser.find_element(:xpath, "//path/to/picture").displayed? }
This would tell the Webdriver to wait a maximum of 10 seconds for the picture element to be displayed. You can also use .enabled? if the element you're waiting for is an interactive element - this is especially useful when you're working with Ajax-based input forms.
You can also declare an explicit wait period at the start of your script, and then reference the object again whenever you need it. There's no need to redeclare it unless you want to set a new timeout. Personally, I like to keep the wait.until wrapped in a method, because I know I'm going to reference it repeatedly. Something like:
def wait_for_element_present( how_long=5, how, what )
wait_for_it = Selenium::WebDriver::Wait.new(:timeout => how_long )
wait_for_it.until { #browser.find_element(how, what) }
end
(I find it's easier to just declare browser as an instance variable so that you don't have to pass it to the method each time, but that part's up to you, I guess?)

ExpectedConditions isn't supported yet in the Ruby Selenium bindings. This snippet below does the same thing as ExpectedConditions.elementToBeClickable — clickable just means "visible" and "enabled".
element = wait_for_clickable_element(:xpath => xpath)
def wait_for_clickable_element(locator)
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
element = wait.until { #driver.find_element(locator) }
wait.until { element.displayed? }
wait.until { element.enabled? }
return element
end

Related

How to wait for object and page load

I wrote this function which is being called after clicking any links or buttons.
Function BrowerSync
If Browser("micclass:=Browser").Page("micclass:=Page").Exist(60) then
BrowerSync = 1
End if
End Function
It works fine most of the cases. However, I am experiencing two issues:
If the browser is already loaded before UFT calls the function, I have seen that UFT is still waiting for the page to be loaded. Instead, it should not wait and move on to the next step.
If UFT calls the function but the browser is not opened, UFT still waits for the browser to open and load. Instead it should not wait and move on to the next step.
How can I edit my function to fix the above two issues?
Your code is not dynamic at all. Also the ideal way to wait is to wait for an element to load in the page (in other word to be visible) that will make sure that the browser loaded successfully. In your case anytime you call the function BrowerSync it waits for to find that object for 60 seconds and then it will exit the function.
I will suggest you that you wait for an element in the page an make it dynamic by using the time as parameter for the method so you can wait sometimes 60 seconds and sometimes 10seconds , based on your browser. Below is my function that i use to wait for a webelement
PageLoad_Performance = 10 'this will be used in DWaitForWebElement Function , set the time in seconds, if time less than time added,element found and pages loaded
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'Function Name: WaitForWebElement
'Description: Its a dynamic Conditional Wait, It will wait for
' Webelement until It Exists
'Arguments: classVal - The class property Value of the Object
' innertextVal - The innertext Value of the object
'Created By:
'Date: 10/25/2016
'Usage: Call WaitForWebElement (classVal,innertextVal)
Function WaitForWebElement(classVal,innertextVal)
Dim Total_Time,oDesc
Total_Time=1
'create description of the object
Set oDesc = Description.Create
oDesc.Add "MicClass","WebElement"
oDesc.Add "class",classVal
oDesc.Add "innertext",innertextVal
With Browser("title:=yourtitleofthepage.*").Page("title:=yourtitleofthepage.*")
'this while loop , it will wait until the object exist , it will never exit the loop unless object is Found
While .WebElement(oDesc).Exist(1) = False
wait 1 ' we loop and check and then wait one second
'every time we loop we increment total time by 1 second , to check at the end to total time to load that page
Total_Time = Total_Time+1
Wend
If Total_Time < PageLoad_Performance Then 'if the page loads in less than 10 seconds Performance Report will Pass
'do your report
Else
'do your report
End If
End With
'clean up
Set oDesc = nothing
End Function

Click to all different next pages into a loop until the last page with Watir gem

i have a problem in my ruby watir script.
I want to click through all next pages until the last page, and then puts some first name and last name. I know that the last "next" link is called with one more class "disabled" stop = b.link(class: 'next-pagination page-link disabled').
I try to loop until this classes is reached break if stop.exists?
loop do
link = b.link(class: 'next-pagination page-link')
name_array = b.divs(class: 'name-and-badge-container').map { |e| e.div(class:'name-container').link(class: 'name-link profile-link').text.split("\n") }
puts name_array
stop = b.link(class: 'next-pagination page-link disabled')
break if stop.exists?
link.click
end
I have this error :
This code has slept for the duration of the default timeout waiting for an Element to exist. If the test is still passing, consider using Element#exists? instead of rescuing UnknownObjectException
/Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/elements/element.rb:496:in rescue in wait_for_exists': timed out after 30 seconds, waiting for #<Watir::Div: located: false; {:class=>"name-and-badge-container", :tag_name=>"div", :index=>13}> to be located (Watir::Exception::UnknownObjectException)
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/elements/element.rb:486:inwait_for_exists'
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/elements/element.rb:487:in wait_for_exists'
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/elements/element.rb:487:inwait_for_exists'
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/elements/element.rb:639:in element_call'
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/elements/element.rb:91:intext'
from /Users/vincentcheloudiakoff/Travail/Automation/lib/linkedin.rb:24:in block (2 levels) in start'
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/element_collection.rb:28:ineach'
from /Users/vincentcheloudiakoff/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/watir-6.2.1/lib/watir/element_collection.rb:28:in each'
from /Users/vincentcheloudiakoff/Travail/Automation/lib/linkedin.rb:24:inmap'
from /Users/vincentcheloudiakoff/Travail/Automation/lib/linkedin.rb:24:in block in start'
from /Users/vincentcheloudiakoff/Travail/Automation/lib/linkedin.rb:22:inloop'
from /Users/vincentcheloudiakoff/Travail/Automation/lib/linkedin.rb:22:in start'
from start.rb:3:in'
It clicks on the next page, but does not find the next disabled button.
Use the text to locate that element
b.span(text: 'Suivant').click
You don't have to use parent link and then span like b.link().span() instead you can directly locate span the way I have explained.

Selenium webdriver ruby: Unable to read text value some times

Scenario:
There is a text in my webpage
I am using xpath to locate it
myxpath=//table[#id='table44']/tbody/tr[1]/td[1]/span[2]
I am trying to get it value using
value=driver.find_element(:xpath, myxpath).text
But problem is :sometimes it gets value & sometime it doesn't
& i am not able to understand the cause of this problem
Any alternative that i can try ?
You can write using explicit wait.
my_xpath = "//table[#id='table44']/tbody/tr[1]/td[1]/span[2]"
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
element = wait.until { driver.find_element(:xpath, my_xpath) }
puts element.text

making 'some_element'.present? in watir wait for less than 5 secs

How do we make some_element.present? or some_element.visible? wait for less than 5 secs.? Because I think some_element.present? alone will wait for default value of 30 secs before timing out.
Thanks
The Element#present? (and Element#visible? and Element#exists?) method does not wait at all. You can see this by checking the time before and after attempting to locate an element that is not present:
puts Time.now
#=> 2014-07-31 22:14:08 -0400
puts browser.element(id: 'does_not_exist').present?
#=> false
puts Time.now
#=> 2014-07-31 22:14:08 -0400
As you can see, the time before and after checking the prescence of the element is a negligible amount.
It should be noted that the above was executed against a tiny page. For a very large page, which would require more inspection, the method could take longer to execute. However, that would be an issue of execution time rather than being Watir is actually waiting.
I believe you are asking how to shorten the length of time before timeout, by default its set to 30 seconds, see below on how to customize that time.
According to http://watirwebdriver.com/waiting/
Explicit waits
There are four built in methods that you can use to make your waiting experience more pleasant (and remove those evil sleep statements from your code)
Watir::Wait.until { ... }: where you can wait for a block to be true
object.when_present.set: where you can do something when it’s present
object.wait_until_present:; where you just wait until something is present
object.wait_while_present:; where you just wait until something disappears
The default timeout for all these methods is 30 seconds, but your can pass an argument to any of these to increase (or decrease) it as needed.
and http://rdoc.info/gems/watir-webdriver/Watir/EventuallyPresent
- (Object) wait_until_present(timeout = nil)
Waits until the element is present.
Examples:
browser.button(:id => 'foo').wait_until_present
Parameters:
timeout (Fixnum) (defaults to: nil) — seconds to wait before timing out
- (Object) wait_while_present(timeout = nil)
Waits while the element is present.
Examples:
browser.button(:id => 'foo').wait_while_present
Parameters:
timeout (Integer) (defaults to: nil) — seconds to wait before timing out
- (Object) when_present(timeout = nil)
Waits until the element is present.
Examples:
browser.button(:id => 'foo').when_present.click
browser.div(:id => 'bar').when_present { |div| ... }
browser.p(:id => 'baz').when_present(60).text
Parameters:
timeout (Fixnum) (defaults to: nil) — seconds to wait before timing out

I am not able to wait in testcomplete for page element to load

I am working on web application, using tool testcomplete with vbscript.
pageTab = Sys.Process("iexplore").IEFrame(0).CommandBar.TabBand.TabButton("Tieto Client Manager").Enabled
do while(pageTab <> True)
Sys.Process("Explorer").Refresh
pageTab = Sys.Process("iexplore").IEFrame(0).CommandBar.TabBand.TabButton("Tieto Client Manager").Enabled
Sys.Process("iexplore").IEFrame(0).CommandBar.TabBand.TabButton("Tieto Client Manager").Refresh
loop
pageBusyState = Sys.Process("iexplore" , 2).Page("*").Busy
do while(pageBusyState <> False)
pageBusyState = Sys.Process("iexplore" , 2).Page("*").Busy
loop
With this code i can wait for new page but not able to wait for control loading page.
The best approach to wait until a dynamic page is ready is to wait for a specific object on this page. For example, this can be the first object you need to work on the page. This approach is described along with a couple of other approaches in the Waiting For Web Pages help topic.
Timeout=False
'Check IEXPLORE Process running on window
If Sys.Process("IEXPLORE").Exists Then
Set obj = Sys.Process("IEXPLORE").Page("*")
Set PageObj = Eval(obj.FullName)
'Set Default Timeout
intDefaultTimeout=1000
'Do until Page Object readyState=4 or Timeout
Do
Set PageObj= Sys.Process("IEXPLORE").Page("*")
'Check for Timeout
If aqConvert.StrToInt(DateDiff("n",intTimerStart,Now))>= aqConvert.StrToInt(intDefaultTimeout) Then
Timeout=True
End If
Loop Until PageObj.ReadyState = 4 Or Timeout=True
Else
'Check iexplore 2 Process running on window
If Sys.Process("iexplore",2).Exists Then
Set obj = Sys.Process("iexplore",2).Page("*")
Set PageObj = Eval(obj.FullName)
'Set Default Timeout
intDefaultTimeout=Project.Variables.prjDefaultTimeout
'Do until Page Object readyState=4(page loaded fully or request finished and response is ready) or Timeout
Do
Set PageObj= Sys.Process("iexplore",2).Page("*")
If aqConvert.StrToInt(DateDiff("n",intTimerStart,Now))>= aqConvert.StrToInt(intDefaultTimeout) Then
Timeout=True
End If
'Check still the page is in busy mode or page loaded fully .
Loop Until PageObj.ReadyState = 4 Or Timeout=True
End If
End If
'Calling Activate method to apply a property collection corresponding to a run mode
PageObj.Activate

Resources