Waruna Gunaratne Waruna Gunaratne - 1 year ago 112
AngularJS Question

How to retrieve data into selenium java script using Angular method

I want to retrieve visitor ID from “visitor” or "visitor.VisitorId" . but below code I use to retrieve data but successfully run without any error but I received value is null.

HTML Code:-

<ul class="sidebar-menu">
<li id="visitorView" class="treeview active">
<ul id="visitorViewMenu" class="treeview-menu menu-open" style="display: block;">
<!-- ngRepeat: visitor in Visitors -->
<li class="ng-scope" ng-repeat="visitor in Visitors" style="">
<a id="visitor.VisitorId" class="ng-binding" ng-click="select(visitor)">
<countryflag class="flagimg ng-isolate-scope" visitor="visitor">
<span class="chattabname"/>
<span class="timmer1 pull-right" runtimer="{"VisitorID":"c2c45b4d-5077-492f-afd6-88ab3bba99cd","Name":"A","StartTime":"2016-09-09 10:33:21","WidgetId":"7fcf22c6-4a9d-4701-9865-b8a85d597862","ConnectionId":"edc7d72b-8217-4961-81ff-f4ef4138bc3b","TimeZone":"Asia/Colombo","CountryCode":"lk","VisitorName":null,"Department":null,"CompanyId":"a4afbd8b-1de9-49d9-8fe6-4ec8119f4bb8"}">
<!-- end ngRepeat: visitor in Visitors -->
<li class="treeview">
<li class="treeview">

Selenium Code:-

**1st method :-**
WebElement cityField = driver.findElement(By.cssSelector("a[ng-click='select(visitor)']"));

**2nd method :-**
WebElement cityField = driver.findElement(By.cssSelector("a[id='visitor.VisitorId']"));

System.out.println("+++-- "+cityField.getAttribute("value"));

Answer Source

Try using getText() which will return innerText of the <a> element as below :-

WebElement cityField = driver.findElement(By.id("visitor.VisitorId"));
System.out.println("+++-- "  + cityField.getText());

Or if you want to get span element where visitorId present in runtimer attribute value, you should locate span element and get runtimer attribute value as :-

WebElement cityField = driver.findElement(By.cssSelector("a[id = 'visitor.VisitorId'] span.timmer1"));
String runtimeData = cityField.getAttribute("runtimer");

//Now do some programming stuff to retrieve visitor id

runtimer attribute data looks like in json format, so you can retrieve any data after converting in into org.json.JSONObject by passing their key as below :-

import org.json.JSONException;
import org.json.JSONObject;

public static Object getValue(String data, String key) throws JSONException {
      JSONObject jObject = new JSONObject(data);
       return jObject.get(key);

String visitorID = (String) getValue(runtimeData, "VisitorID");

Output :-


As OP suggested, we can use split() function as well to retrieve data as :-

String[] splitS = runtimeData.split(","); 

for(int i =0; i < splitS.length; i++) 
  System.out.println("splitS" + splitS[i]); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download