Selenium-C#: SendKeys timing out & JS Executor throwing error - javascript

Trying to paste the data(which is quiet big) in the "Textarea1" control, below are the two methods I tried using, but first method tries pasting the data but throws timeout error sometime, and second one throws JS error. please help
public StringBuilder PasteDataIn_Tarea1
{
set
{
//Method1
Textarea1.Clear();
Textarea1.SendKeys(value.ToString());
//Method2
IWebDriver driver;
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
StringBuilder javascript = new StringBuilder();
javascript.Append(string.Format("$('#Textarea1').text('{0}')", value));//value has my data which is quiet big, "Textarea1" is where I need to paste my data
js.ExecuteScript(javascript.ToString()); // Js exector which should paste my data
}
}
Method2 throws below exception:
An exception of type 'System.InvalidOperationException' occurred in
WebDriver.dll but was not handled in user code
Additional information: JavaScript error (UnexpectedJavaScriptError)
I prefer going to Method2 as the first one takes time to paste the data in the textarea.

Try resetting the browser timeout:
ChromeOptions options = new ChromeOptions();
options.AddArgument("--disable-extensions");
ChromeDriverService svc = ChromeDriverService.CreateDefaultService();
IWebDriver driver = new ChromeDriver(svc, options,TimeSpan.FromMinutes(5));
The example above takes the command timeout to 5 minutes. I had a similar problem and this is what worked for me.

Related

Synchronization problems with automated testing Angular website with Selenium and testing issues with Internet Explorer.

I am trying to write an automated test program for one of my website using Selenium WEbDriver. I am having some problems when doing the test on Internet Explorer. The website that I am trying to test is built in AngularJS. I will explain my problems in detail.
Here, is the code that waits until Angular has finished processing.
private static ExpectedCondition angularHasFinishedProcessing() {
return (ExpectedCondition<Boolean>) driver -> {
String hasAngularFinishedScript = "var callback = arguments[arguments.length - 1];\n" +
"var el = document.querySelector('html');\n" +
"if (!window.angular) {\n" +
" callback('false')\n" +
"}\n" +
"if (angular.getTestability) {\n" +
" angular.getTestability(el).whenStable(function(){callback('true')});\n" +
"} else {\n" +
" if (!angular.element(el).injector()) {\n" +
" callback('false')\n" +
" }\n" +
" var browser = angular.element(el).injector().get('$browser');\n" +
" browser.notifyWhenNoOutstandingRequests(function(){callback('true')});\n" +
"}";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
assert javascriptExecutor != null;
String isProcessingFinished = javascriptExecutor.executeAsyncScript(hasAngularFinishedScript).toString();
return Boolean.valueOf(isProcessingFinished);
};
}
private void waitForAngular() {
WebDriverWait wait = new WebDriverWait(driver, 15, 100);
wait.until(angularHasFinishedProcessing());
}
And here is the code that instantiates WebDriver for Internet Explorer.
System.setProperty("webdriver.ie.driver",
new File("H:/libraries/webdrivers/IEDriverServer.exe").getAbsolutePath());
DesiredCapabilities d = DesiredCapabilities.internetExplorer();
// To bypasse the Protected Mode settings of IE
d.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(d);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://arandomangularjsapp.com"); // Let's suppose this
I had to bypass the Protected Mode settings (shown in above code) because I was constantly getting this Exception
Caused by: org.openqa.selenium.WebDriverException: Unexpected error launching Internet
Explorer. Protected Mode must be set to the same value (enabled or disabled) for all
zones. (WARNING: The server did not provide any stacktrace information)
though I made sure that protected mode was enabled and same values were set for all zones.
Now comes the real issue I am having. Look at this block of code,
waitForAngular();
WebElement el = driver.findElement(By.xpath("//div[#class='events-list__event-info' and #id='48040']" +
"//following-sibling::div[#class='events-list__event-buy']/a"));
if(driver.toString().toUpperCase().contains("INTERNETEXPLORER"))
el.sendKeys(Keys.ENTER);
else
el.click();
waitForAngular();
webElement = driver.findElement(By.xpath("(//div[#class='ticket u-cf ng-scope'])[1]//select"));
select = new Select(webElement);
select.selectByIndex(1);
My first question, the way I am trying to wait for Angular app to get ready by calling waitForAngular(), is it a good way? In my program I even had to use Thread.sleep() so many times in order to let elements to properly render before I could invoke actions on them. It would be great if you guys can suggest me a proper way to use Selenium WebDriver along with Angular App.
Now let's talk about my second issue. I had to completely disable Protected Mode from Internet Explorer's options in order to run the program. Otherwise, I would get this exception,
Caused by: org.openqa.selenium.JavascriptException: JavaScript error in async script. (WARNING: The server did not provide any stacktrace information)
I get this exception when trying to execute waitForAngular(). What could be causing this? Is there any way by which I could keep the Protected Mode enabled and still be able to execute that script inside angularHasFinishedProcessing() method?
Finally, my third problem is related to click action not being triggered. Forget about the previous issues for a second. I disabled IE's Protected Mode, so my program starts IE without throwing any exception. The program successfully finds the first element as shown in the code above. But, the click action is not triggered, browser thus doesn't navigate to next page, and the program fails to find the second element. As a workaround I even tried el.sendKeys(Keys.ENTER); but it didn't work.** So, am I having this problem because I bypassed/disabled Protected Mode? Or, is there something else that I am not being able to see?**
I run tests on IE, Opera, Chrome and Firefox and the problem seems to occur only in IE. Any sort of help, suggestions or guidelines are highly appreciated.
Thank You.

programmatically print a web page

I am making a program to automatically go to a website and print a page, Can't seem to make it work, I tried selenium chrome driver, problem is it doesn't work. i tried action.sendkeys keys ctrl + shift + p to no avail, the biggest problem is print preview pop-up.
I tried sending JavaScript command: window.print(), but the print preview in chrome stands in my way, because you need to press enter. Is there a way in JavaScript to simulate the pressing of the ENTER key? Help would be appreciated.
Well, after a bit of research, I found this video, if you can add these switches: "--kiosk --kiosk-printing", to the chrome driver start, it would automatically skip the print preview prompt, just as shown in the video.
also, I tested this on the latest version of SRWare iron(fork of chromium), and it worked.
If you are using C# to make your program, then there is an easier solution:
private void Button1_Click(object sender, EventArgs e)
{
PrintHelpPage();
}
private void PrintHelpPage()
{
// Create a WebBrowser instance.
WebBrowser webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(#"http://www.google.com"); //This is what you want to change
}
private void PrintDocument(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
// Print the document now that it is fully loaded.
((WebBrowser)sender).Print();
// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
Found the answer in Here, this uses the WebBrowser control to navigate to a specific Url, can be a local url or from the internet, and prints it using your default printer.
Maybe you could you use this approach that doesn't require windows forms, worked like a charm for me:
With C# use Chrome to covert HTML to PDF
var process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var chrome = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles(x86)"), #"Google\Chrome\Application\chrome.exe");
// use powershell
process.StartInfo.FileName = "powershell";
// set the Chrome path as local variable in powershell and run
process.StartInfo.Arguments = "$chrome='" + chrome + #"'; & $chrome --headless --print-to-pdf='c:\Users\" + Environment.UserName + #"\desktop\myReport.pdf' https://google.com";
process.Start();

script to extract information from a webpage in a browser

Background
I have a network performance testing tool which after every test,displays all its results in a new results page. Below is my workflow to find the final value.(Details not relevant here but the html elements i am looking for might
1.Go to a section called "Data frame" ( which has a table with timestamp,transmit,recieve and percentage as columns) and get the time stamp when percentage first drops below 99.9
Here is a snippet of the "Data Frame" table
Data frame snippet
2.Go to another section called "Data throughput" ( table with timestamp, throughput as columns) and get the maximum value of throughput before the previously found timestamp.
After every test, i have to do this manually, but there should be someway to automate this.
Question
1.Is it possible to write a script ( maybe in javascript ) to automate my workflow for every new results page?
example algorithm
section = webpage.section_with_title("Data frames")
for each row in section
find first my_timestamp with percent < 99.9
done
section2 = webpage.section_with_title("Data Throughput")
for each row in section2
find max row.throughput if row.timestamp < my_timestamp
don
2.Once i write the script, how do i execute it in the web page?
3.Can i leverage the firefox/chrome developer console in some way ?
Note:I develop mostly in C,C++ and ruby with very basic experience in HTML and CSS. I have barely used javascript, but i have a vague idea that the browsers use it to handle the content of every page.
My thought process was to somehow execute the script through firefox console, and it will provide me with the results... is that difficult?
edit: since i am not familiar with the web development terms, ill put an a different choice of words...
1.i open up the results page
2.i open the console window of firefox/chrome
3.run my script(dont know what language).
4.i should get the result in the console. i do not want to modify the results page. i just need the result displayed to me(in the console, or to a text file).
Yes it's possible to do what you think using Javascript. Please look up XMLHttpRequest
Here is a way for you to start (in Java):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class YourClass
{
private WebDriver webDriver = null;
public void open() throws Exception
{
webDriver = new FirefoxDriver();
}
public void close() throws Exception
{
webDriver.quit();
}
public void doStuff() throws Exception
{
WebElement element = webDriver.findElement(By.id(...));
...
// Alternatively, it might be easier to parse the entire
// page-source instead of searching elements in the DOM
String pageSource = webDriver.getPageSource();
...
}
}
You will need to download the following JAR files and add them in your project's class-path:
selenium-java-2.xx.0.jar (currently xx=39)
selenium-server-standalone-2.xx.0.jar (currently xx=39)

Want an exception upon BIRT JavaScript errors

I have a report in BIRT that has non-trivial JavaScript (scripted data source). The JavaScript is all a bit wobbly, and suspect to regress. For that reason and others I have written a JUnit test that populates the data, runs the report (createRunAndRenderTask and run that task) and do some validation on the resulting report.
Obviously this test will fail when the BIRT engine throws any exceptions. However, upon JavaScript errors in the report, no exceptions are thrown. And that does not feel good. Can I change this somehow to have the BIRT engine throw exceptions upon JavaScript errors?
I tried this by having a host of JavaScript errors during development of the report. Think of typos in the scripted data source. They are spit out in the console, but no exceptions.
E.g.:
<method name="open"><![CDATA[count = 0;
this should break]]></method>
This shows in the console:
... Fail to execute script in function __bm_OPEN(). Source:
------
" + count = 0;
this should break + "
-----
A BIRT exception occurred. See next exception for more information.
ReferenceError: "this should break" is not defined. (/report/data-sets/script-data-set[#id="9"]/method[#name="open"]#3)
Thank you for your suggestions!
I ended up doing this and pretty okay with it:
IRunAndRenderTask task = ...
...
task.setErrorHandlingOption(IEngineTask.CANCEL_ON_ERROR);
...
task.run();
evaluateStatus(task, reportName);
task.close();
And:
private void evaluateStatus(IRunAndRenderTask task, String reportName) {
if (task.getStatus() == IEngineTask.STATUS_CANCELLED) {
String message = "report failed: " + reportName;
List<Throwable> errors = task.getErrors();
if (!errors.isEmpty()) {
throw new RuntimeException(message, errors.get(errors.size() - 1));
}
throw new RuntimeException(message);
}
}
Depending on javascript errors, the BIRT engine will catch them and still try to display the report.
I think you could override this by wrapping your javascript code (Rhino script) in a try...catch expression, and explicitely throw a BirtException if something wrong happens:
try{
//your javascript stuff
var test=null;
test.toString();
}catch(e){
var exception=new org.eclipse.birt.core.exception.BirtException("Custom exception:"+e);
throw exception;
}

Error: Unable to get value of the property 'length:' object is null or undefined

I have this error in my WebBrowser
Error: Unable to get value of the property 'length:' object is null or undefined
even though I have this code:
CType(TabControl1.SelectedTab.Controls.Item(0), WebBrowser).ScriptErrorsSuppressed = True
Why am I getting this and how do I get rid of it?
If you are creating the Webbrowser componenet dynamically, I suggest that you set ScriptErrorsSurpressed = True at that point.
Dim wb as New WebBrowser
wb.ScriptErrorsSurpressed = True
'Other declarations...
If it is not created dynamically, then I suggest that you go to the control and manually change the setting to True in the design view.
If this doesn't work, please refer to my request/comment on your original post.
EDIT 1
This is your code:
Dim Browser As New WebBrowser
TabControl1.TabPages.Add("New Page")
Browser.Name = "Web Browser"
Browser.Dock = DockStyle.Fill
TabControl1.SelectedTab.Controls.Add(Browser)
AddHandler Browser.ProgressChanged, AddressOf Loading
AddHandler Browser.DocumentCompleted, AddressOf Done
int = int + 1
CType(TabControl1.SelectedTab.Controls.Item(0), WebBrowser).GoHome()
CType(TabControl1.SelectedTab.Controls.Item(0), WebBrowser).ScriptErrorsSuppressed = True
This is how I would write it:
Dim Browser As New WebBrowser
Browser.Name = "Web Browser"
Browser.Dock = DockStyle.Fill
AddHandler Browser.ProgressChanged, AddressOf Loading
AddHandler Browser.DocumentCompleted, AddressOf Done
TabControl1.TabPages.Add("New Page")
TabControl1.SelectedTab.Controls.Add(Browser)
int = int + 1
Browser.GoHome()
Browser.ScriptErrorsSurpressed = True
I see no need for CType() at all.
Your getting the error because the javascript file (www-home-vflVATumV.js) on the http://s.ytimg.com server in the yts/bin folder has an error or has found a dynamic error with the LENGTH property of whatever object it is trying to assess.

Categories