Find a button on a web page looking for part of its InnerText string in Visual Studio - visual-studio-2013

I am writing automated tests for a website. On the website there is a button that will have the inner text "All Open" + four random digits. For example: "All Open2957". Is there a way to find the button using only the "All Open" part of the string?
This does not work since the string is missing the four last digits:
HtmlSpan uIAllOpenPane = new HtmlSpan();
uIAllOpenPane.SearchProperties[HtmlDiv.PropertyNames.InnerText] = "All Open";

The simple answer is to use the PropertyExpressionOperator.Contains rather than PropertyExpressionOperator.EqualTo comparator and search for just the required text.
For recorded tests, find the control in the UI Map editor and view its properties panel. Click the "Search properties" field and then click the ellipsis. The window that appears allows the comparator and the required text to be altered.
For hand coded tests use code of the form:
uIAllOpenPane.SearchProperties.Add(HtmlDiv.PropertyNames.InnerText,
"All Open",
PropertyExpressionOperator.Contains);
According to this Microsoft blog the array index style (ie with [ and ]) as used in the question internally calls the SearchProperties.Add(...) but that style has no variation to specify ...Contains, so call the ...Add(...) explicitly.

Check this out
Button allOpenButton = (Button)BrowserWindow.ExecuteScript("allOpenButton = function(){var found; $('input[type=\"button\"]').each(function(){ if($(this).val().indexOf('All Open') > -1){ found = $(this);};}); return found;}; return allOpenButton();");

When trying to locate the controller I only got the FailedToPerformActionOnHiddenC‌​ontrolException. Eventually I was able to locate the DIV container that contained the controller I was trying to locate instead of focusing on finding the controller directly. After finding the container I could locate the controller using
HtmlSpan uIAllOpenPane = new HtmlSpan(container);
uIAllOpenPane.SearchProperties.Add(HtmlDiv.PropertyNames.InnerText, "All Open",
PropertyExpressionOperator.Contains);
The code from #AdrianHHH helped with the problem when part of the string is randomized each time you encounter the controller.

Related

Loop through drop down with dynamic html table

I'm hard stuck with this one so any advice welcome!
Ive been trying to create a flow that goes to this website https://dlv.tnl-uk-uni-guide.gcpp.io/ and scrapes the data from each table in the Subject Areas drop down list. My knowledge of HTML is sketchy at best but from what I understand it's a dynamic html table that just refreshes with new data rather than going to a new url. I can extract the subject list as a variable and in my head i think i just need to add this to a UI selector action but despite numerous attempts i've got absolutely nowhere. Anyone got any ideas as to how i could fix this or work around?
Because it is not a conventional drop-down using the "Set drop-down list value on web page" doesn't work all that well.
You can use a bit of javascript and variables for this.
Hit F12 to show developer tools, you will see there is a list of hidden items with the class class="gug-select-items gug-select-hide" you will use this in the javascript.
Then add a 'Press button on web page' function and add the 'drop-down' element, which is a <div>
Then edit the element selector and change it to text editor.
then change the selector to make use of the nth-child(0) selector but use a variable for the index.
so it looks something like #gug-overall-ranking-select > div.gug-select-items > div:nth-child(%ddIdx%)
Use the "Run JavaScript function on web page" function to get the number of options available to the drop-down. (child elements)
The returned result is text, so convert it to a number that can be used in the loop.
function ExecuteScript() { /*your code here, return something (optionally); */
var firstDDlist = document.querySelector("#gug-overall-ranking-select > div.gug-select-items.gug-select-hide");
return firstDDlist.children.length;
}
In the loop each element will be pressed and cause the table to reload.
The table data extraction can then also be done in the loop, but that this code only shows the looping through the options.
The full flow 'code' (copy this and paste it in power automate).
WebAutomation.LaunchEdge.LaunchEdge Url: $'''https://dlv.tnl-uk-uni-guide.gcpp.io/?taxonomyId=36&/#gug-university-table''' WindowState: WebAutomation.BrowserWindowState.Normal ClearCache: False ClearCookies: False WaitForPageToLoadTimeout: 60 Timeout: 60 BrowserInstance=> Browser
WebAutomation.ExecuteJavascript BrowserInstance: Browser Javascript: $'''function ExecuteScript() { /*your code here, return something (optionally); */
var firstDDlist = document.querySelector(\"#gug-overall-ranking-select > div.gug-select-items.gug-select-hide\");
return firstDDlist.children.length;
}''' Result=> numberOfItems
Text.ToNumber Text: numberOfItems Number=> itemCount
LOOP ddIdx FROM 1 TO itemCount STEP 1
WebAutomation.PressButton.PressButton BrowserInstance: Browser Control: appmask['Web Page \'h ... sity-table\'']['Div \'gug-select-selected\''] WaitForPageToLoadTimeout: 60
END
It should end up looking like this:
Flow running:
With using Power Automate Desktop (PAD), the goal is to be a low-code solution. Of course knowing HTML is a bonus and will help you on tricky webpages or problems, but not knowing much is alright usually. I'm not really comfortable going to that web page you shared but you could try the below option.
PAD has a built in function in the action pane:
'Browser automation' > 'Web data extraction' > 'Extract data from web page'
Try using that and when asked to add UI Element select the table/dropdown list to see what information you get back. If that doesn't work you might need to try out JavaScript or another method.

Link directly to a notebook page in a view

I have an view that extends the current project view, where we add multiple tabs (notebook pages) to show information from other parts of a project.
One of these pages is an overview page that summarizes what is under the other tabs, and I'd like to link the headlines for each section directly to each displayed page. I've currently solved this by using the index of each tab and calling bootstrap's .tab('show') method on the link within the tab:
$(".overview-link").click(function (e) {
e.preventDefault();
var sel = '.nav-tabs a:eq(' + $(this).data('tab-index') + ')';
$(sel).tab('show');
});
This works since I've attached a data-tab-index="<int>" to each header link in my widget code, but it's brittle - if someone adds a tab later, the current indices will be broken. Earlier I relied on the anchor on each tab, but that broke as well (and would probably break if a new notebook page were inserted as well).
Triggering a web client redirect / form link directly works, but I want to show a specific page in the view:
this.do_action({
type: 'ir.actions.act_window',
res_model: 'my.model.name',
res_id: 'my.object.id',
view_mode: 'form',
view_type: 'form',
views: [[false, 'form']],
target: 'current'
});
Is there any way to link / redirect the web client directly to a specific notebook page tab through the do_action method or similar on FormWidget?
If I understood well you want to select the tab from the JavaScript (jQuery) FormWidget taking into account that the id could change if anybody install another module that adds another tab
Solution 0
You can add a class to the page in the xml form view. You can use the id of the element selected by this class name in order to call the right anchor and select the right tab item. This should happen when the page is completely loaded:
<page class="nb_page_to_select">
$('a[href=#' + $('.nb_page_to_select').attr('id') + ']').click()
NOTE: As you have said the following paragrah I assume that you know where to run this instruction. The solution I suggest is independent of the index.
This works since I've attached a data-tab-index="<int>" to each
header link in my widget code, but it's brittle - if someone adds a
tab later, the current indices will be broken. Earlier I relied on the
anchor on each tab, but that broke as well (and would probably break
if a new notebook page were inserted as well).
Solution 1
When the page is loaded you can get the tab list DOM object like this:
var tablist = $('ul[role="tablist"]')
And then you can click on the specifict tab, selecing by the text inside the anchor. So you don't depend on the tab index:
tablist.find('a:contains("Other Information")').click()
I think if you have two tabs with the same text does not make any sense, so this should be sufficient.
Solution 2
Even if you want to be more specific you can add a class to the notebook to make sure you are in the correct notebook
<notebook class="nt_to_change">
Now you can use one of this expressions in order to select the tab list
var tablist = $('div.nt_to_change ul.nav-tabs[role="tablist"]')
// or
var tablist = $('div.nt_to_change ul[role="tablist"]')
Solution 3
If the contains selector doesn't convince you because it should be equal you can do this as well to compare and filter
tablist.find('a').filter(function() {
return $.trim($(this).text()) === "Other Information";
}).click();
Where "Other Information" is the string of the notebook page
I didn't tried the solution I'm giving to you, but if it doesn't work at least may be it makes you come up with some idea.
There's a parameter for XML elements named autofocus (for buttons and fields is default_focus and takes 1 or 0 as value). If you add autofocus="autofocus" to a page in XML, this page will be the displayed one when you open the view.
So, you can try to add this through JavaScript, when the user clicks on the respective link -which honestly, I don't know how to achieve that by now-. But you can add a distinctive context parameter to each link in XML, for example context="{'page_to_display': 'page x'}". When you click on the link, I hope these context keys will arrive to your JS method.
If not, you can also modify the fields_view_get method (here I wrote how to do that: Odoo - Hide button for specific user) to check if you get the context you've added to your links and add the autofocus parameter to the respective page.
As you said:
This works since I've attached a data-tab-index="" to each header
link in my widget code, but it's brittle - if someone adds a tab
later, the current indices will be broken.
I assume that your app allow multi-user interaction in realtime, so you have to integrate somewhere in your code, an update part function.
This function will trig if something has changed and cleanout the data to rebuilt the index in order to avoid that the current indices will be broken.

Searching on pressing enter button using selenium not working with Firefox

I have the below code. What I actually want to do is enter a string in text field and click on enter. Then search results should be displayed.
But here on 'element.sendKeys(Keys.ENTER);' application logs out. I checked with URLs. URLs should be same after searching.But it changes here.
This code works for Chrome and IE. Issue only with Firefox only.I checked the element type to confirm the clicking. It was text box only.
public static void pressEnterKey(WebDriver driver,WebElement element){
System.out.println("Current URL1" + driver.getCurrentUrl());
WebElementType elementType = WebElementHelper.findElementType(element);
System.out.println("Element Type = " + elementType);
element.sendKeys(Keys.ENTER);
System.out.println("Current URL2" + driver.getCurrentUrl());
}
There is a bug report regarding this issue, it seems to be specific with .NET and FireFox.
See here:
https://code.google.com/p/selenium/issues/detail?id=2079
The result would be to use
element.sendKeys(Keys.Return);
If the sole purpose is to click on the "Enter" button, instead of sending "Enter" keys why not click on the respective element.
Just replace the code element.sendKeys(Keys.ENTER); in your code above with either of the below code(s):
element.click();
OR
element.submit();
On another note, as per the definition, sendKeys method is used to type into an element. And, I am pretty sure you can't type into a button. :)

Make a click event based on a control's name value property

I'm using TestComplete for the automation of QA process.
TestComplete detects click events based on the postion of the mouse on the screen. But when I run the same test on a different machine (a larger/smaller screen) the mouse button won't click on the correct position.
Therefore I want to know is there a method which I can search a control based on its name (i.e. name of a button) and then run a script to click on that particular word (or position).
Any help is appreciated :)
Additional Details
This is a sample script generated by TestComplete for clicking the search button on a web page.
Sub Test6()
'Opens the specified URL in a running instance of the specified browser.
Call Browsers.Item(btIExplorer).Navigate("http://www.simplyrecipes.com/search/?cx=003084314295129404805%3Ai2-mkfc4cai&cof=FORID%3A11&q=&sa.x=48&sa.y=16")
'Clicks at point (173, 10) of the 'textboxQ' object.
Call Aliases.browser.pageHttpWwwSimplyrecipesComSearc.panelPage.headerMasthead.group.panelSiteSearch.formSearchbox0030843142951294048.textboxQ.Click(173, 10)
'Sets the text 'asd' in the 'textboxQ' text editor.
Call Aliases.browser.pageHttpWwwSimplyrecipesComSearc.panelPage.headerMasthead.group.panelSiteSearch.formSearchbox0030843142951294048.textboxQ.SetText("asd")
'Clicks at point (57, 12) of the 'imagebuttonSa' object.
Call Aliases.browser.pageHttpWwwSimplyrecipesComSearc.panelPage.headerMasthead.group.panelSiteSearch.formSearchbox0030843142951294048.imagebuttonSa.Click(57, 12)
End Sub
Here is the button click event captured in the RecordTest window
What I want to know is, is there a way I can specify the control name (i.e 'Search' or 'imagebuttonSa'), so the TestComplete will search for the name in the given GUI and then once it's found, make a click event on the word.
I'm using Windows 7 64bit OS, TestComplete 9 trial version and VBScript as the scripting language.
As far as I can see, TestComplete already works in your case with specific controls/objects: textboxQ and imagebuttonSa. These two names are given to objects by the Name Mapping functionality and you are free to change them as you like.
As for the coordinates, these coordinates are related to the top left corner of the corresponding control (textboxQ or imagebuttonSa). If you want, you can remove the coordinates from the action parameters (e.g. ...imagebuttonSa.Click()) and TestComplete will click the central point of the control.
In case you have any problems with playing back your tests and you cannot find out what the cause of these problems is, the best option for you will be contacting the SmartBear support team with detailed explanation of what happens. Send them your project with failed results logs.
Whenever I have a problem with not finding an object with TC I use one of this functions or a combination of them.
In case you have the table object (parent of the cell you want to click):
function clickCellByText(text,tablePath)
{
var table = tablePath;
if (!table.Exists)
{
Log.Error("A table with the following text cannot be found: " + table);
}
clickCell1(table, "*Cell*", "*Cell*");
function clickCell1(table, idText, linkText)
{
var propArray = new Array("innerText", "ObjectType");
var valArray = new Array(text,"Cell*");
var idCell = table.FindChild(propArray, valArray, 20000);
if (idCell.Exists)
{
// Row found, find the link in the same row
idCell.Click();
}
else
{
Log.Error("A cell with the following text cannot be found: " + text);
}
}
}
If you want to find the object or the parent of the object by any property:
function clickComponent(property,text)
{
// Using the Find method
var myObj = Sys.Browser("iexplore").Page("*").NativeWebObject.Find(property,text);
// Checks if the button exists
if (myObj.Exists)
{
myObj.Click();
}
else
Log.Error("Can't find the object","");
}
If you don't specify co-ordinate, it will click at the center of the object.
You can try doing FindChild or Find with the Object Name Mapping where the button resides, with Properties like (Eg:ObjectType as Button and Button Caption with your required button caption), once the FindChild finds the button with above specified properties you can use that object to click on it:
var button = ParentObj.FindChild(["ObjectType","Caption"],["Button","OK"],10);
if(button.Exists)
button.Click()

How to open and handle richtext editor in javascript in sitecore 6.5?

I've been working on a custom field, which contains a list.
I have to be able to edit the selected item on the list in a richtext editor. (this is the only missing part).
I've read the topic on opening from c# code Opening Rich Text Editor in custom field of Sitecore Content Editor .
This works nice for the "add" button, since i have to open the RTE empty(with default text...), but not for the Edit button.
My aproaches are:
Somehow in the Edit button's message field list:edit(id=$Target) pass the selected index (like list:edit(id=$Target,index=$SelectedIndex), but i don't know how to populate $SelectedIndex
Somehow in the overridden HandleMessage method get the list's selected index. I'm able to get the selected value Sitecore.Context.ClientPage.ClientRequest.Form[ID of list], but thats alone not much of a help, since i won't be able to decide which one to edit if two listitem equals.
Do the richtext editor opening and handling fully in javascript. As i saw at some script in content editor, i tried to do that, but i can't understand it clearly:
richtext editor url:
var page = "/sitecore/shell/Controls/Rich Text Editor/EditorPage.aspx";
some params :
var params = "?da=core&id&ed=" + id + "&vs=1&la=en&fld=" + id + "&so&di=0&hdl=H14074466&us=sitecore%5cadmin&mo";
and the part where i'm not sure:
var result = scForm.browser.showModalDialog(page + params, new Array(window), "dialogHeight:650px; dialogWidth:900px;");
This way the RTE opens as expected (i guess i could get the selected index from javascript and pass it as a parameter later). However when i click ok, i get exception from EditorPage.js saveRichText function: Cannot read property 'ownerDocument' of null. Am i missing some parameter?
Either of the three aproaches is fine for me(also i'm open for new better ones) as soon as i'm able to do it.
Thanks in advance!
Tamas
I was able to enter some javascript into the message:
list:Edit(id=$Target,index='+document.getElementById(ID of the select using $Target ).selectedIndex+')
this way i got the index in HandleMessage.
I'm waiting for better solutions now.

Resources