How to construct an XPath which remove text from <br> tag? - selenium

I am trying to fetch text before the <br> tag using XPath & Java. I tried multiple solutions, but had no luck yet.
//div[#class="help-block"]/p[count(preceding-sibling::br) < 1]
This is my HTML code:
<div class="help-block">
<p>
This is sample text
<br>
Text after a breakpoint
</p>
</div>
Expected outcome: This is sample text.
Actual outcome: This is sample text Text after a breakpoint

To get the This is sample text Induce WebDiverWait And visibilityOfElementLocated() And get the element.
Induce JavascriptExecutor And get the textContent of firstChild
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='help-block']/p")));
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return arguments[0].firstChild.textContent;",element));

I think you can just run this:
driver.find_element_by_xpath("//p[br]").text
This will get the <p> element, but the query also checks to make sure that <p> contains a <br> element inside it. So you are just getting the <p>, and .text should get the text from the <p>.

Your expression was close. But you didn't take into account that p is only one element and you want subnodes of p. So change your expression to the following (also escaping the < char)
//div[#class="help-block"]/p/node()[count(preceding-sibling::br) < 1]
It's output is:
This is sample text

Related

How to locate an element with div format in Selenium. getting error Unable to locate an element with the xpath expression

Below is the code :
<div class="footer-bottom-left">
<div class="campaignUser">Campaign User</div>
<div class="callLogLookUp">Call Log Look Up</div>
</div>
I have tried the below code in selenium:
driver.findElement(By.xpath(".//div[#class='footer-bottom-left'].//div[#class='callLogLookUp']")).click();`
You missed dash in class name. Also you need to remove second dot (first is also not required). So instead of
.//div[#class='footer-bottomleft'].//div[#class='callLogLookUp']
try
//div[#class='footer-bottom-left']//div[#class='callLogLookUp']
You might also need to implement ExplicitWait:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='footer-bottom-left']//div[#class='callLogLookUp']"))).click();

how to get element inside custom tag in chrome web driver

This is my sample html code.
<div class="content">
<M class="mclass">
<section id="sideA">
<div id="mainContent">
<div class="requestClass">
<span>Check</span>
<input type="text" id="box">
</div>
</div>
<section>
<section id="sideB">
...
<section>
</M>
</div>
I want to set some value to my text field ("box"). So I tired to set like below code
driver.findElement(By.xpath("...")).sendKeys("SetValue");
My Xpath id is correct, it's exist in the page but am getting this error
no such element: Unable to locate element: {"method":"xpath","selector":"id("..."}
Why I am getting this error because of my custom tag,if yes how to get element inside custom tag?
As per the HTML you have provided to fill in some value to the text field represented by <input type="text" id="box"> you can use either of the following line of code:
cssSelector :
driver.findElement(By.cssSelector("section#sideA input#box")).sendKeys("SetValue");
xpath :
driver.findElement(By.xpath("//section[#id='sideA']//input[#id='box']")).sendKeys("SetValue");
If you still want to use XPath. This worked for me-
driver.FindElement(By.XPath(#"//*[#id='box']")).SendKeys("AB‌​");
I don't think the custom tag causes any problem as the CssSelector also works-
driver.FindElement(By.CssSelector(#"m[class='mclass'] input")).SendKeys("AB");
You can use ID or xpath to locate it, My suggestion you have to use ID. Also use Explicit wait till element to be visible.
Using ID, your code is like this:
WebElement elem= driver.findElement(By.id("box"));
WebDriverWait wait=new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(elem));
elem.sendKeys("test");
You can also use JavascriptExecutor
WebElement elem= driver.findElement(By.id("box"));
WebDriverWait wait=new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(elem));
JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
myExecutor.executeScript("arguments[0].value='test';", elem);

How to Send Text to Text Box which have same xpath

In Selenium Webdriver we have three Text boxes. All the text boxes have the same Id, and I want to send some text in the second text box.
This is my code:
Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
Could anyone please help how to handle Text boxes which have same Id ?
Currently i m using below code which always send same text for all the three text boxes.
List<WebElement> textfield1 = Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
for(int i=0; i<textfield1.size();i++){
WebElement local_textfield1=textfield1.get(i);
String value1=local_textfield1.getAttribute("placeholder");
if(value1.equalsIgnoreCase(""))
{
local_textfield1.sendKeys("Amarendra Singh");
}
}
There are two ways to get the second textbox.
Method 1: using find elements
List<WebElement> textfields = Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
textfields.get(1).sendKeys("Amarendra Singh");
Method 2: using xpath
WebElement textfield2 = Driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[2]"));
textfield2.sendKeys("Amarendra Singh");
You can use an array like trick to access each element matching the XPath
WebElement textField1 = driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[1]"));
WebElement textField2 = driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[2]"));
The quickest and easiest way I know to do this is to use an XPath to specify the expected ID and placeholder = "" and then specify the index of the element you want.
Given an HTML example of
<html>
<div id="testInstanceScan" placeholder="">e1</div>
<div id="testInstanceScan" placeholder="">e2</div>
<div id="testInstanceScan" placeholder="">e3</div>
</html>
The code below works
List<WebElement> searchBox = driver.findElements(By.xpath("//div[#id='testInstanceScan'][#placeholder='']"));
System.out.println(searchBox.get(1).getText());
and returns
e2
which is the element that contains the desired ID, empty placeholder attribute value, and is the second element. This form of XPath can be tailored to a lot of different situations to get the desired element in a single pass instead of looping or filtering the collection.
In your case, your final code would look like
List<WebElement> textfields = driver.findElements(By.xpath("//input[#id='testInstanceScan'][#placeholder='']"));
textfields.get(1).sendKeys("Amarendra Singh");
If that still doesn't work, you may need a wait.
By locator = By.xpath("//input[#id='testInstanceScan'][#placeholder='']");
List<WebElement> textfields = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
textfields.get(1).sendKeys("Amarendra Singh");
I don't know exactly what is yoyr question but what i understand you want to perform operation on textbox which have same xpaths
This is a sample Html which I used for example
<html>
<div id="test" placeholder="">element1</div>
<div id="test" placeholder="">element2</div>
<div id="test" placeholder="">element3</div>
<div id="test" placeholder="">element4</div>
</html>
First use findElements() to extract all elements and then use if loop to select one and perform operation This is my code
WebDriver driver=new FirefoxDriver();
driver.get("URL");
List<WebElement> allElements=driver.findElements(By.xpath("//div[#id='test']"));
for (WebElement tempElement : allElements) {
if(tempElement.getText().equalsIgnoreCase("element2"))
{
System.out.println(tempElement.getText()); // you can perform your operations
}
}

Using Selenium to select text

Want to select the text "This is for testing selector" from below HTML code.
<div class="breadcrumb">
<a title=" Home" href="http://www.google.com/"> Home</a>
<span class="arrow">»</span>
<a title="abc" href="http://www.google.com/">test1</a>
<span class="arrow">»</span><a title="xyz" href="http://www.google.com/">test2</a>
<span class="arrow">»</span>
This is for testing selector
</div>
I'm not sure if there an easy way out for this or not. It turned out to be more difficult than I thought. Below mentioned code is tested locally and giving correct output for me ;)
String MyString= driver.findElement(By.xpath("//div[#class='breadcrumb']")).getText();
//get all child nodes of div parent class
List<WebElement> ele= driver.findElements(By.xpath("//div[#class='breadcrumb']/child::*"));
for(WebElement i:ele) {
//substracing a text of child node from parent node text
MyString= MyString.substring(i.getText().length(), MyString.length());
//removing white spaces
MyString=MyString.trim();
}
System.out.println(MyString);
Let me know if it works for you or not!
Try with this example :
driver.get("http://www.google.com/");
WebElement text =
findElement(By.className("breadcrumb")).find("span").get(1);
Actions select = new Actions(driver);
select.doubleClick(text).build().perform();
I suggest also that you copy the xpath for the text you need and put it here to have the exact xpath
You cannot select text inside an element using xpath.
Xpath can only help you select XML elements, or in this case, HTML elements.
Typically, text should be encased in a span tag, however, in your case, it isn't.
What you could do, however, is select the div element encasing the text. Try this xpath :
(//div[#class='breadcrumb']/span)[3]/following-sibling::text()
You could try Abhijeet's Answer if you just want to get the text inside. As an added check, check if the string obtained from using getText() on root element contains the string obtained from using getText() on the child elements.

Using Selenium, xpath gets tags but text is empty

I'm using Selenium WebDriver to fetch a bunch of tags via XPATH. The xpath successfully finds the tags, but the "Text" attribute for the returned IWebElements is empty.
Here's the HTML:
<ul>
<li id="foo1">someValue</li>
<li id="foo2">someOtherValue</li>
</ul>
And the xpath:
//ul/li[startswith(#id, 'foo')]
Any ideas? The Xpath definitely grabs the right elements, but the Text element is empty.
Try this code to get the text of 2nd element - <li id="foo2">someOtherValue</li>
:
WebElement fooEle = driver.findElement(By.xpath("//descendant::ul/li[starts-with(#id,'foo')][2]"));
String fooEleText = fooEle.getText();
System.out.println("foo Element Text -" + fooEleText); //should print expected text "someOtherValue"
Note- if you want to get the 1st element text, then change the index value of the xpath
That is, //descendant::ul/li[starts-with(#id,'foo')][1]