How to retrieve the label text as per the html provided? - selenium

Sometimes I failed to get the inner text of a web-element; recently working on thePersonal insurance, and failed to get inner text of label (web element). Here are the script and screenshot of webpage inspected:
WebElement detailPostCode =driver.findElement(By.xpath("//label[#for='q_codePostalDetailAU']"));
System.out.println("postcode label text "+detailPostCode.getText());
Could any please help me understand the problem. Thank you for your kind concern.

As per the HTML you have shared the <label> with text as Postal code is a child node of the <div> tag with class attribute as q_codePostal.
What went wrong?
As per your code trial you have used:
WebElement detailPostCode = driver.findElement(By.xpath("//label[#for='q_codePostalDetailAU']"));
In this expression //label[#for='q_codePostalDetailAU'] will always refer to the descending <input> tag with id attribute as q_codePostalDetailAU. Hence your code trial didn't work.
Solution
As an alternative you can use the following solution:
WebElement detailPostCode = driver.findElement(By.cssSelector("div.q_codePostal>label"));

Can you try this xpath:
driver.findElement(By.xpath("//div[#class='q_codePostal']/label"));

Related

How can I check that a dropdown field is disabled using selenium?

I am trying to write a function in selenium to check if a Reasons dropdown is showing as disabled, but can't quite get the xpath right. The code for the dropdown is in the pic, the function I'm working on is the second one (InputDisabled), having based it on the working first one (SearchDisabled):
` public By SearchDisabled(string searchId) => By.XPath($"//div[#id='{searchId}']//div[contains(#class, 'v-input--is-disabled')]");
public By InputDisabled(string inputId) => By.XPath($"//div[#id='{inputId}']//div[contains(#class, 'v-input--is-disabled')]");`
The inputId going into it is 'ai-confirm-allergy-modal-reason'. I've tried it as 'input[contains...' and 'contains(#disabled, 'disabled'...' among other things, but my xpath knowledge isn't great yet!
dropdown code
Use below code
String value = driver.findElement(By.XPath("//input[contains(#id, 'ai-confirm-allergy')]").getAttribute("disabled");
Assert.AssertEquals(value, "disabled");
I do not quite get your question.
well if you are trying to use xpath to locate an element, you can just use the id; assuming that it is unique.so:
driver.findElement(By.xpath("//input[contains(#id, 'ai-confirm-allergy')]")
should locate the webelement.
However, your xpath for the SearchDisabled is locating a div containing class 'v-input--is-disabled' with in another div with id of '{searchId}';
the same logic goes for the next one. your xpath is trying to locate a div containing class 'v-input--is-disabled' which is located with in another div located using input id. I don't think this combination can locate the element highlighted in the picture.

Selenium: How to find text on page containing html tags? (Text Node)

I updated the question after it was answered!
I try to find a text in a list on the webpage, which contains a html tag like <p> text </p>.
Heres a screenshot how it does look like on the webpage:
Screenshot of text to search for
Inside the "inspect" i used //*[text()='<p> First do this, then this</p>'] which could be found as seen above in the screenshot.
In the code im using this codeline to find the text:
webDriver.FindElement(By.XPath("//*[text()='<p> First do this, then this</p>']"))
But during the test run it gives this error message:
OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[text()='
First do this, then this']"}
As you can see, selenium does somehow ignore the html tags <p> </p>
Answer and solution from cruisepandey:
Thanks to #cruisepandey i know now, my text is inside a textnode.
The only way to get the text out is using this code:
var ele = webDriver.FindElement(By.XPath("//table[#class='mud-table-root']//tbody/tr[1]/td[2]"));
Console.WriteLine(ele.Text);
The output of this here is:
<p> First do this, then this</p>
That's a text node, you cannot simply use text() method from xpath v1.0
You can try with below xpath :
(//table[#class='mud-table-root']//tbody/tr)[1]/td[2]
Code:
var ele = webDriver.FindElement(By.XPath("//table[#class='mud-table-root']//tbody/tr[1]/td[2]/text()"));
Console.WriteLine(ele.Text);
Code (With explicit waits) : in you want to click on it.
var ele = new WebDriverWait(webDriver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("(//table[#class='mud-table-root']//tbody/tr)[1]/td[2]")));
Console.WriteLine(ele.Text);
p is the element tag name, not part of it's text.
Also possibly there are spaces in the text. In this case I prefer using contains instead of exactly equation text check.
Try this instead:
webDriver.FindElement(By.XPath("//p[contains(text(),'First do this, then this')]"))

Identifying an element from a group, span[i] is the differentiating factor

I have added the screenshot I have a group of elements that have the exact same xpath except the span tag.I want to identify the individual input fields, but unable to.
I have tried using contains, with class but unable to attach span to the xpath
Here is what the HTML looks like:
/html/body/div[#id='app']/div/div[#class='LayoutModify_LayoutModify_1Akxb']/main[#class='LayoutModify_main_5aBy3']/section[#class='sub-detail inner ProductDetail_productdetail_bJWN2']/div[#class='ProductDetail_productsphere_kgNGm']/div[#class='ProductDetail_threecol_2zA1n ProductDetail_productsphereleft_2pLZT']/span[4]/div[#class='el-input el-input--medium ProductDetail_productsphereinput_3eVZg']/input[#class='el-input__inner']
/html/body/div[#id='app']/div/div[#class='LayoutModify_LayoutModify_1Akxb']/main[#class='LayoutModify_main_5aBy3']/section[#class='sub-detail inner ProductDetail_productdetail_bJWN2']/div[#class='ProductDetail_productsphere_kgNGm']/div[#class='ProductDetail_threecol_2zA1n ProductDetail_productsphereright_3BrqC']/span[4]/div[#class='el-input el-input--medium ProductDetail_productsphereinput_3eVZg']/input[#class='el-input__inner']
Notice the span[4] and span[15] are the only differences
Quick question:
do either of these locators:
locator A
//span[4]/div/input[#class='el-input__inner']
locator B
//span[15]/div/input[#class='el-input__inner']
find any input on Your page?
If not - could You please post here the whole HTML page code here please?
Here is the xpath that worked:
//div[contains(#class,'ProductDetail_productsphereright')]/span[4]/div/input

How to write a XPath for the text one4

I want to use XPath to locate a link behind a text.
I want to use XPath to locate a link behind a text. For example, locate "one4" by "what10". You can only use the text message "what10", but you can't use it in any other way, because the information on this page will change. I want to get is the "one4" link node.
<body>
<p>
so
<br>what1 one
<br>what2two
<br>what11one4
<br>what3three
<br>what4one1
<br>what5two2
<br>what6three3
<br>what7one3
<br>what8two3
<br>what9three3
<br>what10one4
<br>just return
<br></p>
</body>
For some special reasons, what I want to pass is that the text of what10 is positioned to one4.
Please help me.
You can use below line
WebElement loginLink = driver.findElement(By.linkText("one4"));
Selenium doesn't supports xpath-2.0 but uses xpath-1.0
The element which you are trying to refer i.e. which contains the text what10 is a Text Node and Selenium can't use it as a reference. So finding the node with text as one4 with reference to the text what10 won't be possible. As an alternative if the desired node is always the last but one node you can use the following solution:
xpath:
driver.findElement(By.xpath("//body/p//a[position()=last()-1]"));
Update
As per #MosheSlavin counter question here is the snapshot to demonstrate that the XPath works perfecto:

How to locate an element using selenium webdriver which doesn't have unique identifier like Name, Id, title etc?

I am new to Selenium. Not sure how to handle this scenario. I am working on a website which has several buttons with following code,
<a class="Some big class name" datacommunication="SelectItem" token="some token number" model-id="Id1" element="button">
<i class="classname">Book Ticket</i>
</a>
<a class="Some big class name" datacommunication="SelectItem" token="some token number" model-id="Id2" element="button">
<i class="classname">Book Ticket</i>
</a>
I tried to click on it using following commands,
ele = driver.FindElement(By.ClassName("Some big class name")); but it fails with following message, Compound class names are not supported. Consider searching for one class name and filtering the results.
ele = driver.FindElement(By.CssSelector("a[model-id='Id1']")); fails with 'Test method TestBot.HomeTest.bookTicket threw exception:
OpenQA.Selenium.WebDriverTimeoutException: Timed out after 10 seconds'
Tried using XPATH,
ele = driver.FindElement(By.XPath("\\\a[#model-id='Id1']")); doesn't work either.
I have no control on html. Can't change it.
Please let me know how to identify elements in such scenarios.
You can't have spaces in class names. Those are actually multiple classes separated by a space. You can find the above elements using a css selector
var ele = driver.FindElements(By.CssSelector(".Some.big.class.name"))
Of course, this will find both elements. To find just the first, you could use
var ele = driver.FindElement(By.CssSelector("a[model-id='Id1']"))
You can find help on css selectors here: http://www.w3schools.com/cssref/css_selectors.asp
Update:
I just noticed your XPath appears to have the slashes the wrong way around. If you wish to use XPath, try
//a[#model-id='Id1']
Note, however, that css selectors perform better than XPath.
There are multiple number of ways to locate your WebElement in Selenium WebDriver.
But always remember all are based on you attribute or combination of HTML tags so case could be any of them
1- First way is using id
2- 2nd one is Name
3- Class Name
4- Some time you can used Tagname
5- Some time linkText
6- Some time partial link text
7- Using xpath
8- Using css selector
So in you case we need to take help of Xpath and Css Selector
So xpath of you elements
Syntax : //[#attribute ='value of selected tag']
Example
id1: //a[#model-id='Id1']
id2: //a[#model-id='Id2']
For both element following are the css Selector
Syntax [attribute ='value']
id1:
a[model-id='Id1']
id2:
a[model-id='Id2']
http://www.slideshare.net/weekendtesting/css-selector-29312437
http://www.slideshare.net/weekendtesting/locators-in-selenium-bnt-09
Thanks a lot for help. I have used following code to overcome above mentioned issue,
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("a[data-model-id='c5']"))).Click();
With above code, I am able to click on the button.
Thanks again for your help and knowledge sharing.
Amit
You can locate by using xpath.
WebElement ele = driver.findElement(By.xpath("//*[#class='Some big class name']"));
there is difference between findElements and findElement.
FindElement: findElement returns a single element.
FindElements : returns a list of same element.As in this example there are multiple classes with same class name , so use driver.findElements method .
driver.findElements will return a list of all elements with that class name .
Now , you have list of all elements but you want only one of the element.
So iterate over list to get a single element out of a list.
List<WebElement> elementList= driver.FindElement(By.ClassName("Some.big.class.name"));
Iterator itr = elementList.iterator();
while(itr.hasNext())
{
WebElement element = itr.next();
if(element.getAttribute("model-id").equals("Id1")){
element.click();
break;
}//if block ends here
}//while loop ends here
You can also use XPATH , if nothing works
To identify the elements in selenium there are multiple ways.
To see the details please refer BY Class.
Try to find the way which can identify the element uniquely. Start with id if available and if nothing works go for XPATH. XPATH is slower than id and CSS selector.