How to grab just element id - using Selenium WebDriver 2 - selenium

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");

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

Getting error while inserting Customized String in xpath in Webdriver

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++;
}

Element present fails due to iframe issue for getting image src using Selenium WebDriver

As we know iframe can be counted using frameslist but that doesn't work for me and gives blank output although frame count gives me count as 2. I'm using Selenium WebDriver and Java.
Basically I want to get img source's data-mce-src starts with cid and dfsrc ends with # according to below screenshot.
I tried :
public static final String imageAttachment="css=img[data-mce-src^='cid']&&[data-mce-src$='#']";
which works fine using sIsElementPresent in selenium 1.0 but it fails in webdriver using findElement. In fact it doesn't identify iframe itself.
Expected:
css=img[data-mce-src^='cid']&&[data-mce-src$='#'] element present?
Code:
WebElement we = null;
List <WebElement> framesList = webDriver().findElements(By.tagName("iframe"));
for (WebElement frame:framesList){
System.out.println(frame.getText()); // returns nothing
}
int listSize = framesList.size();
webDriver().findElement(By.xpath("//iframe"));
System.out.println(listSize);
Also tried:
webDriver().switchTo().frame(webDriver().findElements(By.tagName("iframe"));
we = webDriver().findElement(By.cssSelector("html body div img"));
System.out.println(we.getAttribute("src")); // returns nothing
You should try as below :-
webDriver().switchTo().frame("Editor1_body_ifr");
we = webDriver().findElement(By.cssSelector("body#tinymce img"));
System.out.println(we.getAttribute("src"));
try {
webDriver().switchTo().frame("Editor1_body_ifr");
we = webDriver().findElement(By.cssSelector("html body img"));
System.out.println(we.getAttribute("src"));
System.out.println(we.getAttribute("data-mce-src"));
System.out.println(we.getAttribute("dfsrc"));
} finally {
webDriver.switchTo().defaultContent();
}

Find text with Selenium in Chrome

How can I get the text 200 in this case:
<p style="margin:0">
You can get <big class="tooltip">200</big> more</p>
I'm trying using:
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.XPath("//*[contains(#class, 'tooltip')]"));
But can not get the text because the .Text property returns an empty string :(
Any thoughts?
You are using ClassName() with Xpath
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.Xpath("//*[#class=\"tooltip\"]/big"));
However, I would use CssSelector in this case since css is always preferred over xpath
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.CssSelector("big.tooltip"));
Considering the element is not inside any iframe since it is not throwing any error, I am assuming the wait is needed. Try the following
By byCss = By.CssSelector("big.tooltip");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(byCss);
});
var text = myDynamicElement.Text;
Looks the element is hidden. So JavaScript is probably your best try.
var text = ((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('.tooltip_health_limit').innerHTML;") as string;
To get the text after you find the element:
string text = currentElement.Text;

The method getAttribute("value") is not working for textbox

I am new to selenium. I am trying to retrieve the value of a textbox. Below is my code.
WebElement e = driver.findElement(By.id("id"));
e.sendKeys("text");
String str = e.getAttribute("value");
System.out.println(str);
The above code is working fine in all sites but is not working for a particular site. I can't share the site details.
Any explanation regarding why the code is not working for a site or is there another way to get the text from a textbox?
getAttribute('value') will provide you with null cause html snippet doesnot contains value attribute or the DOM object of that element has no value attribute. Try getting the text with :
String str = e.getText(); //If it helps
OR
use JavascriptExecutor as
JavascriptExecutor js = (JavascriptExecutor) driver;
String str = js.executeScript(
"return document.getElementById('company').value")
.toString();