Looping a list through a column in webdriver - java

If I'm expecting a page to display 5 offers, how would I tell webdriver to list all those 5 offers in a ul?
The Ul html code is
<ul id="more-load" class="product_list_widget pagination-centered" style="padding-top:15px;">
I think you would use
List<WebElement> allElements = driver.findElements(By.xpath("//div[#id='more-load']/ul/li"));
for (WebElement element: allElements) {
System.out.println(element.getText());
}
but I'm not sure how to print each individual offer in the Ul and match the 5 offers expected to be displayed
EDITED CODE
never mind used this and worked
WebElement allElements = driver.findElement(By.id("more-load"));
List<WebElement> liElements = allElements.findElements(By.tagName("li"));
for (int i = 0; i < liElements.size(); i++)
{
System.out.println("-------------------------------------------------------");
System.out.println(liElements.get(i).getText());
}
however if I have a column on the left side, with ul = product categories, how would I loop it to go through each individual link text and preform the same function

Let's say your 5 offers are as below:
Offer1
Offer2
Offer3
Offer4
Offer5
now your approach is correct till for loop:
then you can do something like :
String offerString = Offer1 + " " + Offer2 + " " + Offer3 + " " + Offer4 + " " + Offer5;
for (WebElement element: allElements) {
if(offerString.contains(element.getText()){
System.out.println("Offer item is: " + element.getText());
}
}

Stick with your original attempt, except change the line:
List<WebElement> allElements = driver.findElements(By.xpath("//div[#id='more-load']/ul/li"));
to
List<WebElement> allElements = driver.findElements(By.xpath("//ul[#id='more-load']/li"));

using java8:
List<String> offers = driver
.findElements(By.cssSelector("#more-load li"))
.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
and you can assert offers.size() to have some expected value by any assert library
To get linked text elements in UL you can use next selector:
driver.findElements(By.cssSelector("ul a"))

Related

Selenium multple xpaths how to select a specific xpath

I am using selenium to select an xpath based on the date but there are two separate dates in the html both that start with td. How do I specify which date to select? Do I place a [2] at the end of the search text?
The line looks like this
List<WebElement> li2 = driver.findElements(by.xpath("//td[contains(text(),'" + date " "')]/preceding::*5[]"
so should I do this
List<WebElement> li2 = driver.findElements(by.xpath("//td[contains(text(),'" + date " "'[2])]/preceding::*5[]"
List<WebElement> li2 = driver.findElements(by.xpath("//td[contains(text(),'" + date " "')]"))
you are using list do you can get the element get (list index starts from 0 )
WebElement li = li2.get(4)
or
you can get 5th result of xpath by enclosing the xpath locator with brackets and calling [5] ( here index starts from 1 )
WebElement li = driver.findElements(by.xpath("(//td[contains(text(),'" + date " "')])[5]"))
If you want to get 5th sibling then don't enclose it with bracket , this will say get the 5th td tag that is a sibling and contains the date
WebElement li = driver.findElements(by.xpath("//td[contains(text(),'" + date " "')][5]"))
To answer my question.
List<WebElement> li2 = driver.findElements(by.xpath("//td[contains(text(),'" + date " "')]/preceding::*5[1]"
Would be how to index this particular xpath.

how to get generalized xpath for object in Selenium webdriver

String str = "some value" ;
getTestBase().getDriver().findElement(By.xpath("//h2[.='" + str + "']//parent::div//div[#id='sectionList'][1]/section/div/button")).click();
I need to put the above in loop so that [1] keeps increasing every time , how can I update the above xpath for the integer ?
String str = "some value" ;
WebDriver driver = getTestBase().getDriver();
for(int i=0; i<5; i++){
driver.findElement(By.xpath("//h2[.='" + str
+"']//parent::div//div[#id='sectionList']["+i+"]/section/div/button")).click();
}
This should solve your problem. 5 is just an arbitrary limit i assumed for writing the solution.
On the other hand you can try and get all the elements and store the elements in a list. Then parse the list to get the the buttons and click on them.
Some thing like:
String str = "some value" ;
WebDriver driver = getTestBase().getDriver();
List<WebElement> listOfButtons = driver.findElements(By.xpath("//h2[.='" + str + "']//parent::div//div[#id='sectionList']//section/div/button""));
for(WebElement el: listOfButtons){
el.click();
}

Java: Trying to get the value of an HTML element

I am trying to extract the value of an HTML table element from a website and compare it to a user input value but it seems that the nested loop is not being entered when I run the program. It works with no errors but I am not getting any output from Eclipse, I'm new to Selenium Java and still learning.
See my code below:
String inputString = basePrem;
try {
//Print to console the value of Base Prem
WebElement table = driver.findElement(By.xpath(".//td[text()='Base Premium']/following-sibling::*"));
List<WebElement> allrows = table.findElements(By.tagName("tr"));
List<WebElement> allcols = table.findElements(By.tagName("td"));
for (WebElement row: allrows) {
List<WebElement> Cells = row.findElements(By.tagName("td"));
for (WebElement Cell:Cells) {
if (Cell.getText().contains(basePrem)) {
System.out.print("Base Premium = "+ basePrem + " ");
}
else if (!Cell.getText().contains(basePrem))
{
System.out.print("Base Premium = " + basePrem + " ");
break;
}
}
}
}
catch (Exception e) {
errorMessage = "Value discrepancy";
System.out.println(errorMessage + " - " + e.getMessage());
driver.close();
}
Also, inputString is where I input the value I use for comparison (I use a separate excel file for testing)
Since the control is not going inside the nested loop, I probably have some logical error?
You can rewrite the code as below and then validate whether your inputstring is available in the table. It is not necessary to use nested for loops
Code:
String inputString = basePrem;
WebElement table = driver.findElement(By.xpath(".//table"));
//Extract all the Cell Data Element
List<WebElement> dataElementList=table.findElements(By.xpath(".//td"));
for(WebElement dataElement : dataElementList){
if(dataElement.getText().contains(inputString)){
System.out.print("Base Premium = "+ basePrem + " ");
break;
}
}

How to get anchor tag href and anchor tag text inside a div using Selenium in Java

My HTML code consists of multiple divs. Inside each div is a list of anchor tags. I need to fetch the href values and text values of the anchor tags that are in the sub-container div. I'm using Selenium to get the HTML code of the webpage.
HTML code:
<body>
<div id="main-container">
One
Two
Three
<div id="sub-container">
Abc
Xyz
Pqr
</div>
</div>
</body>
Java code:
List<WebElement> list = driver.findElements(By.xpath("//*[#href]"));
for (WebElement element : list) {
String link = element.getAttribute("href");
System.out.println(e.getTagName() + "=" + link);
}
Output:
a=www.one.com
a=www.two.com
a=www.three.com
a=www.abc.com
a=www.xyz.com
a=www.pqr.com
Output I need:
a=www.abc.com , Abc
a=www.xyz.com , Xyz
a=www.pqr.com , Pqr
Try this,
List<WebElement> list = driver.findElements(By.xpath("//div[#id='sub-container']/*[#href]"));
for (WebElement element : list) {
String link = element.getAttribute("href");
System.out.println(element.getTagName() + "=" + link +", "+ element.getText());
}
You can use element.getText() to get the link text.
If you only want to select the links in the sub-container, you can adjust your xPath:
//*[#id="sub-container"]/a
Pretty simple, try as below:
`List<WebElement> list = driver.findElements(By.xpath("//div[#id='sub-container']/a"));
for (WebElement element : list) {
String link = element.getAttribute("href");
String text = element.getText();
System.out.println(e.getTagName() + "=" + link + ", " + text);
}
if id sub-container is unique, just use the below line
driver.findElements(By.cssSelector("div#sub-container>a"));
thanks

xPath not finding selector when using for-each loop variable, but works otherwise

I'm using Selenium to loop through an ArrayList of Strings in order to use each string in an xPath expression in order to select its appropriate checkbox on a website.
The problem is, when I use the for loop, the variable containing the string doesn't seem to create a valid xPath, yet when I simply substitute the string in myself it works fine.
For example, here is my ArrayList declaration with some values added.
ArrayList<String> fieldList = new ArrayList<String>();
fieldList.add("Street");
fieldList.add("City");
fieldList.add("Country");
If I then use the following code, it goes into the catch block
WebDriverWait waitForElement = new WebDriverWait(driver, 1);
for (String cField: fieldList) {
try {
waitForElement.until(ExpectedConditions.elementToBeClickable(By.xpath("//td[following-sibling::td[2] = " + cField + "]/input")));
WebElement checkBox = driver.findElement(By.xpath("//td[following-sibling::td[2] = " + cField + "]/input"));
checkBox.click();
} catch (Exception error) {
System.out.println("Couldn't find " + cField);
}
}
Telling me it couldn't find "Street" for example.
Yet when my try block contains the following, with the value explicitly stated, it works:
waitForElement.until(ExpectedConditions.elementToBeClickable(By.xpath("//td[following-sibling::td[2] = 'Street']/input")));
WebElement checkBox = driver.findElement(By.xpath("//td[following-sibling::td[2] = 'Street']/input"));
What am I doing wrong? Thanks a lot.
You are forgetting to quote your strings in the XPath expression. Add single quotes around cField:
waitForElement.until(ExpectedConditions.elementToBeClickable(
By.xpath("//td[following-sibling::td[2] = '" + cField + "']/input")));
// quotes added here ---^ and here ---^
WebElement checkBox =
driver.findElement(By.xpath("//td[following-sibling::td[2] = '" + cField + "']/input"));
// quotes added here ---^ and here ---^

Categories