How to get specific HTML element under current WebElement - java

After i found specific WebElement and do all my stuff (clicks etc.) is it possible to get let say another WebElement under this WebElement that i already have without FindElement again ?
For example:
WebElement element = driver.FindElement(By.Xpath("..."));
Now i know that under this element i have lats say dpan that i want so is it possible to reach this span from that element i already found ?

it will be better if u give ur html code portion. From my guess, lets say u have html code like this:
div id = "one"
span
span
now if u want to access the 2nd span element, use
cssSelector
and inside this, write code like this:
By.cssSelector("#one.span:nth-child(2)")
here
# is used for id

The WebElement interface also has a findElement method that can be used to find an element relative to one that has already been found.
Here's an example implementation of it:
// Find the parent element
WebElement parentElement = driver.findElement(By.id("parent"));
// Find the child element relative to the parent element
WebElement childElement = parentElement.findElement(By.id("child"));

Related

How to identify and click this span in java with selenium?

I can't get xpath of this html as it gives me error and the test case gives failure
I tried by class name of it's outer div or button
WebDriverWait wait2 = new WebDriverWait (ChromeBroswerObject, 5);
WebElement element2 = wait2.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"root\"]/div/div/div[3]/div/div[2]/section[2]/div/div[1]/a/p[1]")));
element2.sendKeys(Keys.ENTER);[enter image description here][1]
If you like to click on all shop now links, then try this,
List<WebElement> links = driver.findElements(By.xpath("//p/span[contains(.,'Shop now')]"));
for(WebElement link : links)
{
link.click();
}
Or if you like just the first shop now link,
WebElement element2 = wait2.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Epic sound for epic study sessions.')]/p/span[contains(.,'Shop now')]")));
element2.click();
It's a bit hard to tell exactly what you're trying to click, but here is my best guess:
css selector:
p.offerCta_Bis60
Xpath:
//p[#class='offerCta_Bis60']
If that's the correct element, but the class attribute changes on you, you could try this xpath:
//p and ./span[text()= 'Shop Now']
For a specific product, you can add text for that, for example this would turn the second example into this:
//a[contains(p/text(), 'Epic sound for epic study sessions.')]/p and ./span[text()= 'Shop Now']
Explanation:
You should identify some attribute you can rely on that will uniquely identify the element, preferably using an id or class.
In the second example, I'm scanning the entire document(//) looking for a p node that also has a child(./) span with the text Shop Now.
You can use this below xpath.
Make sure to replace x with the desired item number.
(//section[#data-automation='dynamic-content-offer-list']//div[contains(#class,'ItemsPerRow')])[x]
Screenshot:
If you want to get all the items in the list and then iterate through them then you can use below xpath with findElements.
//section[#data-automation='dynamic-content-offer-list']//div[contains(#class,'ItemsPerRow')]
If you want to get the paragraph under link, then simply extend the xpath as below.
(//section[#data-automation='dynamic-content-offer-list']//div[contains(#class,'ItemsPerRow')]/a/p)[1]
To click() on the element with text as Shop now as the element is a dynamic element you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ta[href*='epic-sound-for-epic-study-sessions'] p[class^='offerCta_']>span"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(#href, 'epic-sound-for-epic-study-sessions')]//p[starts-with(#class, 'offer')]/span[text()='Shop now']"))).click();
First locate the parent <p> element preferably by partial text using XPath contains() function
Then locate following-sibling (next node having the same parent)
And finally filter the resulting <span> by its text
//p[contains(text(), 'Save up to')]/following-sibling::p/span[text()='Shop now']
References:
XPath Tutorial
XPath Axes
XPath Operators & Functions

How to get Text from a div element returns just a "." with Selenium

I have a div element which looks like below.
I identify this element with the following xpath.
//*[contains(#class,'ce-component-title')]
Selenium identifies this element and loads the WebElement object. But when I go to get its text, I'm just getting a "." as shown below instead of getting "Purchase to pay process". What am I doing wrong here? I checked the chrome console and there's no other element matching this xpath.
Any help would be much appreciated.
As per the HTML you have shared the element is an Angular element so you have to induce WebDriverWait for the desired element to be visible and you can use either of the following solutions:
cssSelector:
String myString = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div[ng-if*='getTitle']>div.ce-component-title"))).getAttribute("innerHTML");
xpath:
String myString = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#ng-if,'getTitle')]/div[#class='ce-component-title flex text-overflow ng-binding']"))).getAttribute("innerHTML");
I think your xpath (//*[contains(#class,'ce-component-title')]) returns more than one element, and the element you need is not the first one.
Try using console of your browser, to verify how many elements this xpath returns.
I can help you if you give me url to this page.

How to click a element if a tag is missing

1
1
I want to do a click on the second element where the outside-month tag is missing. How can I achieve this?
Is there a special selenium function or do I have to write a special xpath expression?
For your scenario I imagine you could devise an XPath expression that uses the not() and contains() operators together.
Something along the lines of:
//a[not(contains(#class, 'outside-month'))]
I haven't tested whether this works or not but let me know if not and I can help refine it.
If outside-month is missing on target element you should use = with class name as below xpath:-
String xPath = "//a[#class = 'ng-binding ng-scope']";
or
if you want to use contains and target element is the last with containing class name you should pass last() as below :-
String xPath = "(//a[contains(#class, 'ng-binding ng-scope')])[last()]";
or
if you want to use contains and target element is not the last element with containing class name you should pass appropriate index as below :-
String xPath = "(//a[contains(#class, 'ng-binding ng-scope')])[2]";
or
if you want outside-month is missing but ng-binding ng-scope present you should try as below :-
String xPath = "//a[contains(#class, 'ng-binding ng-scope') and not(contains(#class, 'outside-month'))]";
Use anyone of the above xPath and perform click as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xPath)));
el.click();
Note :- Be ensure before finding element that it is not inside any frame. If it is inside any frame you need to switch that frame first as :- driver.switchTo().frame("frame name or id")
Hope it will help you..:)
in that element outside-month it's not a tag or attribute it's just a bigger class name
so what you need is to find a tag that have ng-binding ng-scope class name:
driver.findElement(By.xpath("//a[#class='ng-binding ng-scope']")).click();

Obtain Selenium WebElement from cssSelector over HTML Input

I am quite new on Selenium (started today) and I would like to get the WebElement corresponding to the following html Input:
<input size="25" style="text-align:center;" value="http" onclick="this.select();" type="text"></input>
And then obtain its value. This is what I have tried so far:
WebElement element = driver.findElement(By.cssSelector(".text-align:center"));
String text = element.getText();
Or this:
WebElement element = driver.findElement(By.cssSelector("input[style='text-align:center']"));
But Java returns in both cases an exception:
org.openqa.selenium.InvalidSelectorException: The given selector
.text-align:center is either invalid or does not result in a
WebElement
Thank you,
Héctor
Do you have to search for the element by cssSelector?
You could give this a try:
WebElement element = driver.findElement(By.cssSelector("input[type='text']"));
If cssSelector is not necessary you could try grabbing the element by xpath.
If you use firefox, there is a plugin called FireBug which allows you to right click after inspecting the element and copying the xpath directly then using :
WebElement element = driver.findElement(By.xpath("XPATH HERE"));
EDIT: Part of post disappeared, redded it.
Your first try is slightly off
driver.findElement(By.cssSelector(".text-align:center"));
The (.) in a CSS selector indicates a CSS class name but that's a style on the element and not a class. There is no class on that element to use in that way.
Your second try looks good but maybe it's not unique on the page? Hard to tell with only the one line of HTML. You'd have to provide more of the HTML of the page. Try it again but get the value instead of text.
WebElement element = driver.findElement(By.cssSelector("input[style='text-align:center']"));
System.out.println(element.getAttribute("value"));
Does that work? You likely will have to provide some unique HTML that surrounds the INPUT that we can use to make the CSS selector more specific.

Selenium Webdriver - Find dynamic id from li/a

I am trying to select a value(Bellevue) from a li(it looks like a dropdown but it isn't).The problem is that its id changes everytime the page loads.
Here is a screenshot:
This time the id is: ui-id-23,but the number,23,will be changed next time so this will not work.If I expand the <a id="ui-id-23..." I get the name 'Bellevue' but every character surrounded by < strong > < /strong > mark-up.
I can't find it after it's classname because both values from li have the same class,ui-menu-item.
I tried after xpath:"//a[contains(text(),'Bellevue')]" but I get the error:Unable to locate element...
Do you know any solution for this?I am using Selenium Webdriver in Java and TestNG.
Thanks!
Update
So I managed to find that element by using:
WebElement value = driver.findElements(By.cssSelector("a[id^='ui-id-']")).get(3);
value.click(); .
but in my application i am using page objects and i look after elements using #FindBy(how.HOW.....).Do you know how I can use .get(3) with #FindBy?
You want to use a CSS selector on the ID:
a[id^='ui-id-']
This says "Find all of the a elements that have an ID that start with ui-id-"
If you want to find the second item, then do:
driver.findElements(By.cssSelector("a[id^='ui-id-']"))[1]
The [1] will select the second item on the page.
It looks like jQuery uniquId() method is used to populated the id, so it will always start with ui-id-. You can use jQuery selector to select element whose id starts with ui-id-
WebElement webElement = (WebElement) ((JavascriptExecutor) webDriver).executeScript("return $( 'input[id^="ui-id-"]').get(0);");
I would try to use xpath avoiding using of id. For example, //a[#class=''ui-corner-all ui-state-focus ][2]
First get the tag name in which your id attribute has been defined.
WebElement ele = driver.findElement(By.tagName(tagName));
String strId = ele.getAttribute("id").startsWith("ui-id-");
driver.findElement(By.id(strId)).click();

Categories