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">
<a>
<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"/>
A
<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"}">
</a>
</li>
<!-- end ngRepeat: visitor in Visitors -->
<li>
</ul>
</li>
<li class="treeview">
<li class="treeview">
</ul>
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']"));
**Output**
System.out.println("+++-- "+cityField.getAttribute("value"));
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");
System.out.println(visitorID);
Output :-
c2c45b4d-5077-492f-afd6-88ab3bba99cd
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]);
}
If I understand correctly the value you are looking for is in the runtimer attribute that located in descendant element of id="visitor.VisitorId", you need to put that in getAttribute() method
WebElement cityField = driver.findElement(By.cssSelector("#visitor.VisitorId > .timmer1"));
String attributeData = cityField.getAttribute("runtimer");
String visitorId = attributeData.split(",");
System.out.println("+++-- " + visitorId);
Output: +++-- "VisitorID":"c2c45b4d-5077-492f-afd6-88ab3bba99cd"
Related
I am currently working on an automation framework using java, selenium, selenium-grid, pageObject with pageFactory.
I am trying to create a method for testing the following html code:
<section class="footer-links">
<div class="footer-layout">
<ul>
<li class="title">Header</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li><a href="/games/download/" >text</a></li>
<li><a href="/games/mobile/" >text</a></li>
<li><a href="/events/" >text</a></li>
</ul>
<ul>
<li class="title">Header</li>
<li><a href="/publishers/" >text</a></li>
<li><a href="/smth/" target="_blank" >text</a></li>
<li><a href="/promo/press/" >text</a></li>
</ul>
<ul>
<li class="title">Header</li>
<li><a href="/support/" >text</a></li>
<li><a href="/support/payment-inquiries/" class="loginModalShow" rel="nofollow" >text</a></li>
<li><a href="/support/general-inquiries/" >text</a></li>
<li><a href="/support/game-inquiries/" class="loginModalShow" rel="nofollow" >text</a></li>
</ul>
<ul>
<li class="title">Header</li>
<li><a href="/blog/" >text</a></li>
<li><a href="/search/" rel="nofollow" >text</a></li>
<li><a href="/directory/pc-games/" >text</a></li>
</ul>
</div>
The code above represents a footer containing 4 lists with some links.
What I am trying to do with the following method is to iterate once through the 4 lists and again inside each list clicking the links and verifying the url to which they redirect against their href attribute value.
#FindBy(css = ".footer-links .footer-layout ul")
public List<WebElement> footerLinksLists;
public void checkFooterLinks(){
if (footerLinksLists.size()==4){
for(int i=0; i<footerLinksLists.size(); i++){
List<WebElement> links = wait.until(ExpectedConditions.visibilityOfAllElements(footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)")))); // footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)"));
for (int j=0; j<links.size(); j++) {
WebElement link = wait.until(ExpectedConditions.elementToBeClickable(links.get(j).findElement(By.cssSelector("a"))));
String href = link.getAttribute("href");
link.click();
if(driver.getCurrentUrl().contains(href)){
log.info("Link " + href +" is ok");
}
driver.navigate().back();
}
}
}else{
log.info("the footer does not contain 4 link lists");
}
}
After starting my test it breaks after entering the for loop with the following error
org.openqa.selenium.StaleElementReferenceException: The element reference of <li> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
In my test class I have the following code for initializing pageobject containing the method:
WebDriver driver = driverFactory.getDriver();
WebDriverWait wait = driverFactory.getWait(driver);
homepagePageObject homePage = new homepagePageObject(driver, wait);
PageFactory.initElements(driver,homePage);
homePage.createAccount();
homePage.checkVerifyAccountRibbon();
homePage.signOut();
homePage.Login();
homePage.checkFooterLinks();
Initially I thought it had something to do with waiting for each element but I am receiving the same error after adding the waits/expectedConditions.
Can somebody explain what am I doing wrong and what would be the best solution in this case?
Because page get refresh and List element lost its value.
You have to manage it By reassign links value.
public void checkFooterLinks(){
if (footerLinksLists.size()==4){
for(int i=0; i<footerLinksLists.size(); i++){
List<WebElement> links = wait.until(ExpectedConditions.visibilityOfAllElements(footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)")))); // footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)"));
for (int j=0; j<links.size(); j++) {
WebElement link = wait.until(ExpectedConditions.elementToBeClickable(links.get(j).findElement(By.cssSelector("a"))));
String href = link.getAttribute("href");
link.click();
if(driver.getCurrentUrl().contains(href)){
log.info("Link " + href +" is ok");
}
driver.navigate().back();
}
links = wait.until(ExpectedConditions.visibilityOfAllElements(footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)"))));
}
}else{
log.info("the footer does not contain 4 link lists");
}
}
This method doesn't do what you want it to do.
First, it only goes through this loop if the number of footerlinks is 4.
If the number of links is changed, or there is a bug that causes it to be 3, the whole method is skipped and you just get a log statement to the fact.
Since there are no assertions, and the method does not return anything, this method will pass every time it is run.
Second, if the link does not contain the expected href, the if-statement won't execute. All that means is that you won't have the OK statement in the logs.
The method will still execute and succeed.
I would suggest to include some assertions with this test. Either as part of each iteration. So something like this:
List<WebElement> links = wait.until(ExpectedConditions.visibilityOfAllElements(footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)")))); // footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)"));
for (int j=0; j<links.size(); j++) {
WebElement link = wait.until(ExpectedConditions.elementToBeClickable(links.get(j).findElement(By.cssSelector("a"))));
String href = link.getAttribute("href");
link.click();
**assertTrue("The expected URL did not match",driver.getCurrentUrl().contains(href));**
driver.navigate().back();
}
or as a return from the method itself
public boolean checkFooterLinks(){
if (!footerLinksLists.size()==4){
return false;
}
for(int i=0; i<footerLinksLists.size(); i++){
List<WebElement> links = wait.until(ExpectedConditions.visibilityOfAllElements(footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)")))); // footerLinksLists.get(i).findElements(By.cssSelector("li:not(:first-child)"));
for (int j=0; j<links.size(); j++) {
WebElement link = wait.until(ExpectedConditions.elementToBeClickable(links.get(j).findElement(By.cssSelector("a"))));
String href = link.getAttribute("href");
link.click();
if(!driver.getCurrentUrl().contains(href)){
return false;
}
driver.navigate().back();
}
}
return true;
}
and then let the test verify the links are ok with
assertTrue("something is not right with the footer links",checkFooterLinks())
What this gives you is that if the number of the links are no 4, or the link opened up does not match the expected, the test will fail.
That said, I can see the value of checking the links and that they contain an expected href value, but I'm not sure what value checking the actual url will give you.
If the href is corrupt, and points to www.google.com, the test will pass as the two values match. Just food for thought.
static By yearFoundErrorMessage = By.className("error");
public static WebElement ca1_YearFoundError(WebDriver driver){
element = driver.findElement(By.id("yearFoundErrorMessage"));
return element;
}
//Main class from where I'm calling above function
String errorMessage = Ca1GeneralInformation.ca1_YearFoundError(driver).getText();
System.out.println(errorMessage);
<div class="controls">
<input id="ca1_GEN_foundedDate" class="error" type="text" value="2008" maxlength="4" name="data[CaInformation][ca1_GEN_foundedDate]" tabindex="5" unsaved="true">
<span id="ca1_GEN_foundedDate_error" class="inline-error ajax-failed-msg">
<span class="error" for="ca1_GEN_foundedDate">Please enter a valid year (i.e. 2013)</span>
</span>
</div>
I'm working on webapplication where there is error message in span I want to get text of this span using webdriver. Above is my html and code.Please help me out.
thanks in advance.
yearFoundErrorMessage is a By variable but you are sending it as string to another By. Try this
public static WebElement ca1_YearFoundError(WebDriver driver) {
element = driver.findElement(yearFoundErrorMessage);
return element;
}
Try below xPath :
WebElement element = driver.findElement(By.xpath("//span[contains(text(),'Please enter a valid year')]");
String message = element.getText();
If i have code like this
Elements e = d.select("div[id=result_52]");
System.out.println("elemeeeeeee" + e);
the output of e is as below
elemeeeeeee<imagebox id="result_52" class="rsltGrid prod celwidget" name="B00BF9MZ44">
<div class="linePlaceholder"></div>
<div class="image imageContainer">
<a href="http://www.abcdefg.com/VIZIO-E241i-A1-24-Inch-1080p-tilted/dp/B00BF9MZ44/ref=lp_6459736011_1_53/190-4904523-2326018?s=tv&ie=UTF8&qid=1405599829&sr=1-53">
<div class="imageBox">
<img src="http://ecx.images-abcdefg.com/images/I/51PhLnnk7NL._AA160_.jpg" class="productImage cfMarker" alt="Product Details" />
</div>
I want both URL which is coming inside
You can use # to get the specific id.
Element e = d.select("div#result_52").get(0);
String firstURL = e.select("a").attr("href"); //select the `a` tag and the `href` attribute.
String secondURL = e.select("img").attr("src");
I need to capture the error messages displayed, i tried many methods but every method throws exception --unable to find element,
pls help with the code. These are the methods i tried.Also, there is no ID, it is div element. something like this...
<div id="webformErrors" class="text" name="errorContent">
<div>
There were 4 errors:
<ul>
<li>
You did not enter a value for:
<b>First Name</b>
</li>
<li>
You did not enter a value for:
<b>Last Name</b>
</li>
<li>
<li>
//String errormsg;
![enter image description here][1]errormsg = Hcd.findElement(By.xpath("//div[#id=webformErrors']/text()")).getText();
// WebElement divElement = Hcd.findElement(By.className("errorContent"));
// Hcd.findElement(By.name("There were 4 errors:")).isDisplayed();
**String pstring = Hcd.findElement(By.id("webformErrors")).getText();
System.out.println(pstring);
You have given the classname and name wrong. classname is "text" and name is "errorContent".
WebElement divElement = Hcd.findElement(By.className("text"));
<div></div>
<div></div>
<div></div>
<div></div>
<ul>
<form id=the_main_form method="post">
<li>
<div></div>
<div> <h2>
<a onclick="xyz;" target="_blank" href="http://sample.com" style="text-decoration:underline;">This is sample</a>
</h2></div>
<div></div>
<div></div>
</li>
there are 50 li's like that
I have posted the snip of the html from a big HTML.
<div> </div> => means there is data in between them removed the data as it is not neccessary.
I would like to know how the JSOUP- select statement be to extract the href and Text?
I selected doc.select("div div div ul xxxx");
where xxx is form ..shoud I give the form id (or) how should I do that
Try this:
Elements allLis = doc.select("#the_main_form > li ");
for (Element li : allLis) {
Element a = li.select("div:eq(1) > h2 > a");
String href = a.attr("href");
String text = a.text();
}
Hope it helps!
EDIT:
Elements allLis = doc.select("#the_main_form > li ");
This part of the code gets all <li> tags that are inside the <form> with id #the_main_form.
Element a = li.select("div:eq(1) > h2 > a");
Then we iterate over all the <li> tags and get <a> tags, by first getting <div> tags ( the second one inside all <li>s by using index=1 -> div:eq(1)) then getting <h2> tags, where our <a> tags are present.
Hope you understand now! :)
Please try this:
package com.stackoverflow.works;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
/*
* # author: sarath_sivan
*/
public class HtmlParserService {
public static void parseHtml(String html) {
Document document = Jsoup.parse(html);
Element linkElement = document.select("a").first();
String linkHref = linkElement.attr("href"); // "http://sample.com"
String linkText = linkElement.text(); // "This is sample"
System.out.println(linkHref);
System.out.println(linkText);
}
public static void main(String[] args) {
String html = "<a onclick=\"xyz;\" target=\"_blank\" href=\"http://sample.com\" style=\"text-decoration:underline;\">This is sample</a>";
parseHtml(html);
}
}
Hope you have the Jsoup Library in your classpath.
Thank you!