Getting error while inserting Customized String in xpath in Webdriver - selenium

Iam trying to locate elements in a webpage. Elements are arranged in rows. For all the rows(or elements), the common attribute is "pfobj". With the help of list interface i have listed out all the elements having attribute pfobj. While finding element with xpath iam getting error. I tried to insert srting pfobj inside xpath argument.
code for a particular element:
WebElement eachelement = driver.findElement(By.xpath("//*[#pfobj=\"pfobj1\"]"));
I want to run for all elements by using loop. so i need to insert "pfobj"(which will iterate by increasing the value) in the place of "pfobj1".
I have tried the several ways but iam getting error:
String slash1 = "\\";
String pfobj = pfobj1;
String slash2 = "\\";
String final = slash1 + pfobj + slash2
Can someone please help me out with this issue

You can try this code :
for ( WebElement element: List) {
if (element.getAttribute("pfobj").equals("pfobj")){
// do what you want
}
}
List is your element list

From what I take from this question is that there are several elements in your HTML having value of pfobj attribute as pfobj1, pfobj2, and so on.
If you want to compare all such elements in a loop, you can do like -
List<WebElement> your_list = driver.findElements(By.xpath("//input[contains(#pfobj,'pfobj')]"))
int counter = 1;
for(WebElement your_element : your_list )
{
if(your_element.getAttribute("pfobj").equals("pfobj" + counter))
{
//do whatever you want
}
counter++;
}

Related

How to pass dynamic value into xpath in selenium, java?

I have a website, where i open contract and get the unique contractId. Then, i need to go to other page and search this id in table with pagination. I wrote code which goes to next page if this requesid(it's a link) is not found and if it exist, it just opens this requestId. But there is a problem with initialization of webelement where i'm trying add dynamic value. Selenium gives error below and i have no idea how to solve it
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[#class='link__text' and text()='222254']/../../..//input"}
(Session info: chrome=89.0.4389.72)
contractId is the variable where i store dynamic value that changes every test run. This is how the code looks like:
csecp.waitForElementVisibility(csecp.getContractStatusEmergencyChangeHeader());
int totalPages = Integer.parseInt(csecp.getTotalPagesString().getText());
for(int i = 0; i < totalPages; i++) {
csecp.sleep(500);
if (**csecp.prepareWebElementWithDynamicXpath(csecp.getContractDynamicValue(),contractId).isDisplayed()**) {
csecp.prepareWebElementWithDynamicXpath(csecp.getContractDynamicValue(),contractId).click();
csecp.waitForElementVisibility(csecp.getConfirmAMLApprovalButton());
csecp.getConfirmAMLApprovalButton().click();
break;
}
csecp.waitForElementVisibility(csecp.getNextPageButton());
csecp.getNextPageButton().click();
}
This is how i'm trying to pass dynamic valueinto xpath
private String contractDynamicValue = "//span[#class='link__text' and text()='xxxxx']/../../..//input";
public WebElement prepareWebElementWithDynamicXpath (String xpathValue, String substitutionValue ) {
return getWebDriver().findElement(By.xpath(xpathValue.replace("xxxxx", substitutionValue)));
}
You can define and use this XPath locator as following:
String contractDynamicValue = "//span[#class='link__text' and text()='%s']/../../..//input";
public WebElement prepareWebElementWithDynamicXpath (String xpathTemplate, String substitutionValue ) {
String xpath = String.format(xpathTemplate,substitutionValue);
return getWebDriver().findElement(By.xpath(xpath));
}
See the xpath that you are using is
//span[#class='link__text' and text()='xxxxx']/../../..//input
and if you wanna make xxxxx as dynamic, you could do following :-
string sub_value = "222254";
//span[#class='link__text' and text()='"+sub_value+"']/../../..//input
It's always the best solution to get element by text and the following element. For dynamic elements, you can use XPath like
//div[.='Dummy_text']/following::span[text()='test_text']
You can see some tutorials from here
https://www.guru99.com/xpath-selenium.html

How to select individual dynamic options of a multi-select through Selenium and Java

Hi I am trying to automate the process where my script will select individual values in the multi-select box and perform some action based on the results. Below is my code. problem with my code is, it will select all the values of a multi-select, instead it should select individual item in the list. All the list values are dynamic in nature and we can't predict what is coming. Requesting your help in this regard!
Values in the multi select are Test 1, Test 2 and so on.
public void filterByTemplateName() throws Exception
{
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("performing action")));
WebElement eventName = driver.findElement(By.xpath(".//select[#name='Test_templateName']']"));
driver.switchTo().frame("test_frame");
Select sel = new Select(templateName);
List<WebElement> options = sel.getOptions();
for (WebElement temp:options)
{
temp.click();
}
}
Since you've initialized this sel variable as a Select object you should be able to use the methods that Select provides for this:
for (WebElement temp:options) {
sel.selectByVisibleText(temp);
}
Does that help?
Considering all of your test criteria of:
Selecting individual item from the list of the multi-select one by one through an iteration.
List values are dynamic.
You can't predict what is coming.
To select individual item from the list you can use the following solution:
WebElement dropdown_element = driver.findElement(By.xpath("xpath_dropdown_element"));
Select templateName = new Select(dropdown_element);
List<WebElement> options = templateName.getOptions();
for(int i=0; i<options.size(); i++)
{
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("./dropdown_element//options"))).get(i).click();
System.out.println("You can perform your other task for this option selection");
}

how to write xpath for this below situation

I have the elements, highlighted in image :
The xpath for the list is //div[#class='list-group formsFilteredList']//a[#class='list-group-item'], but I need the text of that a tag. The text of that are changes dynamically. So I cannot use text contains method
Try this:
//div[#class='list-group formsFilteredList']//a[#class='list-group-item']/text()
You could find the element by class name instead of xpath but there are several elements with the same class name so what you could do is get the elements into a list and work with them from there:
List<WebElement> lstElements = driver.findElements(By.className("list-group-item"));
Then if you know where in the list the element is that you want to use, you can specify the index. For example if you want to click the second item in the list you'd do this:
lstElements.get(1).click();
If you want to do something with each of the items in turn then iterate through them in a for loop:
for (int i = 0; i < lstElements.size(); i++ ) {
System.out.println("List item text: " + lstElements.get(i).getText());
}

Selenium script for selecting value from dropdown as per value given by user from console

I have added a image (Stripe.com) i want to select a specific value from drop down as per user pass from console.Please help me with this.
As Per my code it is taking zero values from drop down to compare with user value.
Here it is
dropdown=driver.findElements(By.xpath("//ul[#id='select2-results-18']//li[#role='presentation']/div/span[#class='card-name']"));
int a1=dropdown.size();
System.out.println(a1);
for(int i=0;i<a1;i++)
{
System.out.println("hhh");
String s1=dropdown.get(i).getText();
System.out.println(s1);
if((s1.compareToIgnoreCase(card))==0)
{
dropdown.get(i).click();
break;
}
else
System.out.println("Fail");
}
Dropdown element type is to be used here which has inbuilt methods to select dropdown options either by text/value or index.
SelectElement dropdown = driver.findElement(By.xpath("//ul[#id='select2-results-18']//li[#role='presentation']/div/span[#class='card-name']"));
dropdown.SelectByText(userInput);
Try this:
Select sel=new Select(wd.findElement(By.xpath("//ul[#id='select2-results-18']//li[#role='presentation']/div/span[#class='card-name']")));
sel.selectByVisibleText(card);
Import import org.openqa.selenium.support.ui.Select; for using Select.
Please make sure you are choosing select element xpath.
Select dropdown = new Select(driver.findElement(By.xpath("XXXXX"));
List<WebElement> list = dropdown.getOptions();
for (WebElement temp : list) {
if (temp.getText().equals("your value").toString()) {
System.out.println("Pass");
}
else{
System.out.println("Try again");
}

How to grab just element id - using Selenium WebDriver 2

EDIT:
I also tried this
var webElements1 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']//input"))).ToList();
I get the empty Text
I am trying to find a way to grab just ID from the list i am getting and below is my code and a print shot of my screen.
//WebDriver getting a list of Text
the below code returns me the correct number of records but it just give me the Text but I am after Text and Id of an particular Text
I tried this:
var webElements1 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']/tbody/tr/td/span"))).ToList();
this
var webElements2 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']/tbody/tr/td"))).ToList();
and this...
var webElements3 = (Driver.FindElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']"))).ToList();
the all code of line gives me the correct returns but without Id.
Here is the print screen of my page:
After getting all the elements using below method, run in loop to get all element's ids:
List<WebElement> element = driver.findElements(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Control1_lstCategory']//input")));
for(WebElement ele:elements)
{
ele.getAttribute("id"); // for getting id of each element
ele.getText(); //for getting text of each element
}
1) i'll try to share the idea of the approach I would choose to resolve your issue:
getElementsByTagName('input');//returns array of elements
2) using js executor get element's attribute , ID in particular, iterating through the whole array returned by getElementsByTagName('input') and getting theirs IDs.
//sample of code I used to find color attribute:
public String jsGetColor(String cssSelector){
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x=$(\'"+css+"\');");
stringBuilder.append("return x.css('color')");
String res= (String) js.executeScript(stringBuilder.toString());
return res;
}
this is simply my assumtion how it be possible to try. hope it somehow helps you)
If you only need one id:
String id = driver.findElement(By.xpath("//*[contains(text(), 'Your text')]")).getAttribute("id");