Detect that automated Chrome page has been closed - excel

I have written code to automate entries into a survey using Excel VBA with selenium controlling chrome.
If the user closes the driven chrome window then currently I get a vba error when the next element can't be found.
I want to write some code to detect the chrome window is no longer present and then close down the vba code smoothly.
My idea was to try to find the tab title and execute the closure code if it did not exist - meaning I got the chrome not available error. The code below seems to work but there is a 13 second wait whilst it looks for the page title. Shortening any of the 4 Timeouts available in selenium basic does not seem to change this wait.
My questions are:
Is there a better way to check if the driven chrome window has closed?
Is there a way to shorten the period of time before the error is thrown?
On Error Resume Next
tabTitle = ch.Title
If Not tabTitle Then
Debug.Print "Closed"
End If
On Error GoTo 0
Many thanks

The only way I know of is to catch UnreachableBrowserException. I am not sure what Selenium version you are using, but in Java, you would surround your code in a try/catch
try {
// do your Excel thing here
} catch (UnreachableBrowserException e) {
// execute your alternate plan
}
The problem is that this could happen at any time, anywhere. You can simply put this everywhere on the code. If this is part of a fully-automated solution, why not simply run your script in headless mode. This will prevent the root cause of the problem which is a user unexpectedly closing the browser.

Related

How to get past command prompt hang without manually hitting enter? [Python - Selenium]

I am trying to webscrape with python via selenium, and for one of the websites, after scraping the information this error pops up:
[11796:3768:0425/173530.772:ERROR:navigation_entry_screenshot_manager.cc(135)] Invalid entry with unique id: 35
A similar error happens when I try to log in to a website(https://www.waug.com/good/?idx=104880) via selenium. My code is:
import selenium.webdriver
option = selenium.webdriver.ChromeOptions()
option.add_argument(' - incognito')
browser = selenium.webdriver.Chrome(executable_path=r"chromedriver.exe")
browser.get('https://www.waug.com/good/?idx=104880')
browser.find_element_by_name('btn-login').click()
browser.find_element_by_id('mem_id').send_keys(myID)
browser.find_element_by_id('mem_pwd').send_keys(myPW)
browser.find_element_by_css_selector("button[type='submit']").click()
Then I get the error: [11364:1060:0425/175320.588:ERROR:navigation_entry_screenshot_manager.cc(135)] Invalid entry with unique id: 5
Now the real problem is that when I get these errors, the program doesn't break but my command prompt just hangs until I manually hit enter. Is there a way to make my program hit enter on its own to get past this error? I'm scraping a bunch of similar websites and I don't want the program to wait for me to hit enter manually before continuing on. For now I don't care too much about why the error is popping up(although it'd be great to know if anyone does know), so maybe is there a way to suppress the error over all?

How do I export runtime datatable into excel if any error occurs due to data?

I want to know if I can export a datatable into excel when I get an error due to data while running the scripts.
If i am having 5 records in a sheet, and 2 records processed well, while running the third record my script encounters an error. Am I able to export into excel in that moment?
Errors may occur at any places because of the data.
Your question doesn't explicitly say QTP, but I'm assuming QTP because you used the tag HP-UFT.
I'm not sure what you mean by "when we get error", so I'll explore two possibilites.
1) You're getting an error in the application you are testing; QTP itself is still executing the script.
In this situation, your script should have validation checks (if statements that check to make sure that what you expected to happen did indeed just happen), and if those checks fail, you could immediately do a DataTable.Export(filename) to save the data to disk before QTP ends. Then, the script could continue, or you can add an ExitTest to fail out and stop the test.
Based on your question, I think it's more likely that:
2) You're getting an error in QTP itself. When QTP crashes, it drops any dynamic changes to the DataTable (i.e. if you had done a DataTable.Import(filename) or updated any fields, it would loose that and go back to it's design time DataTable instead)
In this situation, your script is encountering something that is causing QTP itself to stop the script. Perhaps it's hitting an error where an object cannot be found, or some kind of syntax error. You should consider adding defensive statements to check on things before your code reaches the point that this kind of error would occur... For example, perhaps add...
If not Browser("ie").Page("page").WebTable("table").Exists then
FailTestBecause "Can't find table"
End If
...
function FailTestBecause (reason)
Print "Test Failed Because: " & reason
Reporter.ReportEvent micFail, Environment("ActionName"), reason
DataTable.Export(filename)
ExitTest
end Function
Or, you could just use an On Error Resume Next and put in a command to DataTable.Export(filename) immediately after where it is failing...

Make Greasemonkey throw error on undefined variable

I've recently switched from chrome to firefox for greasemonkey development. I have some problems with debugging.
The following func
I meant to write:
self = this;
but instead I wrote
this=self;
Self wasn't defined, so the script didn't run, however, nor did I get any javascript error. Why and can I get them somehow? I get some errors.
Unfortunately, Greasemonkey - and javascript in general, along with at least a few other non-compiled languages - do not give very good debugging errors... I can't count the number of times it tells me there is a missing ) at the end of an argument list that doesn't exist, and it turns out my error is elsewhere...
When a script of mine won't run I add an alert after any value assignments and if they don't alert or alert the wrong data I have found the problem... for your example above I would debug by:
this=self;
alert(self);
Although I would probably see the problem when I went to add the alert, but if I didn't notice - the alert either wouldn't pop up or it would have the wrong value... and if it didn't pop up, the error console would likely say self not defined.

Excel Object SaveAs, error happens when Existing File is Open

Excel_Obj = CREATE OleObject
Excel_Obj.ConnectToNewObject( 'excel.application' )
Excel_Obj.Workbooks.Add
Excel_Obj.Application.ActiveWorkbook.WorkSheets.Add
Excel_Sheet = Excel_Obj.Application.ActiveWorkbook.WorkSheets[1]
//EXAMPLE
Excel_Sheet.Cells[1,1] = 45
Excel_Obj.Application.ActiveWorkbook.SaveAs(ls_file,56) //csv
//where ls_file = the Opened File
error happened after / during saveas.
try catch throw "error calling external object..in click..line.. saveas.."
--
i want to state to the user that the excel file is open therefore cannot be overwritten properly. I used a try catch and throwed a proper message but before the messagebox for the catch event happens, the PB execution error R0035 happens. any solutions or proper way to know if the excel file is open.
You might be able to check if the file is open first, have a look at this answer:
how to check if file is opened in excel using OLE (leaves excel process open)
I'd try a PowerScript FileOpen () call with a LockReadWrite! parameter to see if it can be opened, followed immediately by a FileClose () if it was successful. (I think this is a PowerScript-specific variation on the DXL solution Colin linked to.)
Good luck,
Terry
Have you tried approaches similar to these?
Using Win32 API:
http://www.rgagnon.com/pbdetails/pb-0030.html
Using PB function fileopen()with the (default) exclusive rights set:
http://www.tek-tips.com/viewthread.cfm?qid=1610670
In other words, see if the file can be opened exclusively before connecting to Excel or making the CSV?
You will have to turn off the option to break into the debugger for that exception to see the exception handling work in the IDE. Look for the Help topic "Exception Settings dialog box" for details. Once you see it's working I recommend you set it back to break into the debugger, since you'd normally want to see what threw the error.
You cannot use ole when document is open( even you set lock write) by the user and not by apllication.
my approach, I have been using many times till now:
Check excel is open or not, use use can use api or wsh script in the internet to check app opened. If opened do not run save as and tell user to close excel and not run it for while for while.
if you user run excel and your program still running active workbook and worksheet application will be switch to excel that opened by user ( imagine it wrong written data).
Change your code as below
if Excel_Obj.ConnectToNewObject( 'excel.application' ) <> 0 then
messagebox("warning", "could connect to excel", stopsign!)
RETURN
end if
just for knowledge another technique is DDE call, but not common today and most complicated.
Happy coding From pb developer.

"object invoked has disconnected from its clients" error message is displayed while working with popup windows

I am trying to work with popup windows. I have gone through the site "http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups". I have modified the "ie-class.rb" by adding the code mentioned in the solution #7 of the site.
Also I have tried the example mentioned below :
require 'watir/ie'
require 'win32ole'
iewin = Watir::IE.new
iewin.goto("http://www.w3schools.com/js/tryit_view.asp?filename=tryjs_confirm")
iewin=Watir::IE.attach(:url, /w3schools/)
iewin.bring_to_front
iewin.maximize
iewin.button(:value, "Show a confirm box").click_no_wait
txt = iewin.clickprompt("OK") # waits for popup and click ok
puts txt #prints the popup text
txt1=iewin.clickprompt("OK")
puts txt1
iewin.close
On executing the following code, popups are handled but produces the following error :
C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:319:in `method_missing': unknown property or method: `name' (NoMethodError)
HRESULT error code:0x80010108
The object invoked has disconnected from its clients.
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:319:in `exists?'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:406:in `close'
from popup.rb:50:in `<main>'
Press a button!
You pressed OK!
But when I remove the command "iewin.close", error message is not displayed.
"iewin.close" command closes the browser and then there is nothing for watir to perform then why is the error message displayed.
Please suggest.
It appears that you are using ruby 1.9.2 with Watir. The watir installation page recommends using Ruby 1.8.7. That should fix the problem.
Good luck,
Dave
Notice that the output you have is not in order. You are seeing the error from closing the browser, BEFORE the output from your Puts.
Not sure if this is a treading issue or what, but in any event it looks from the output like the window is attempting to close before stuff that is dependent on it has finished. Perhaps try inserting a brief sleep for a second or five right before you try to close the window and see if you are still having issues.
Dug into this a bit. It appears that Ruby 1.9 is throwing a "NoMethodError" instead of a "WIN32OLERuntimeError". The Watir IE code reads as such
def exists?
begin
!!(#ie.name =~ /Internet Explorer/)
rescue WIN32OLERuntimeError
false
end
end
To fix this a second rescue can be added to the call
def exists?
begin
!!(#ie.name =~ /Internet Explorer/)
rescue WIN32OLERuntimeError
false
rescue NoMethodError
false
end
end
I don't know the side effects of adding such a call, but it does suppress the close warning.

Resources