Sahi Pro - How do I extract partial text that changes dynamically?
This case is slightly different from Extracting dynamic text. Here the entire text does not change, but only part of it.
Let us look at a couple of examples.
Example 1: An Amount div that shows "Rs 600", where the amount 600 is variable. The text will always contain "Rs" however. We want to extract the amount, i.e. 600.
Example 2: A Page indicator div that shows "Page 2 of 5". Here 2 and 5 are variable but the rest of the content is not. We want to extract the current page number, i.e. 2 and the total pages i.e. 5.
Example 1
Consider a div's visible text shows Rs 600. We wish to extract 600 from it.This is how we can do it.
-
Sahi identifies a div through the visible text, by default. The main problem is in identifying the div since the amount can keep changing. So the div cannot be identified as _div("Rs 600") since 600 is variable.
So use one of the following methods to get a unique identifier.
-
Since part of the text does not change, see if you can use a regular expression on the unchanged text to uniquely identify the div. Example:
_div("/Rs/")
.
-
If there is another div containing "Rs", then we cannot reliably identify our div as
_div("/Rs/")
since there is more than one div containing "Rs".
So try to identify the div in relation to some other anchor element using a Relation API such that the identifier remains unique.
Example: We may be able to identify this as_div("/Rs/", _in(<some other container>))
where<some other container>
identifies a container element, say another div.
-
Or use an alternative for the div which does not change (Look at the Alternatives dropdown in the Recorder tab of the controller)
-
Since part of the text does not change, see if you can use a regular expression on the unchanged text to uniquely identify the div. Example:
-
Once the div is identified, use _getText.
-
Once the text is identified, use the _extract API to extract the partial text.
Working code:
var $amount = _getText(_div("/Rs/")); // Assuming that _div("/Rs/") uniquely identifies the div.
var $number = parseInt(_extract($amount, "/Rs (.*)/", true));
Example 2
Another example would be to extract the current page number and total pages from a PageIndicator div that says "Page 2 of 5".This div can be identified as _div("/Page .* of/").
Working code:
var $str = _getText("_div("/Page .* of/")");
var $pages = _extract($str, "/Page (.*) of (.*)/", true);
var $currentPageNumber = parseInt($pages[0]);
var $numPages = parseInt($pages[1]);