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

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

Related

Unable to locate elements on a website , i tried all the locators but I get the error "No such element" . I am a self taught beginner to Automation

Element HTML:
Inbox
What I tried:
driver.findElement(By.cssSelector("a[text='Log out']"));
then
driver.findElement(By.xpath("//a[.='Log out']"));
Element snapshot:
HTML
driver.findElement(By.linkText("Log out"));
Something like that should work, you should provide the page html for a better response.
My response is based on the fact that in your first try you are saying text='Log out'.
findElement in selenium works with locatorStrategies (By.cssSelector/By.linkText...) the one that i used (linkText) search in all the anchor tags that are found in the pages () and analyze the text inside the tag, if the text is matched the driver will find the element.
Let me know if it works, otherwise provide me the web page html snippet.
I've seen the actual screen, you must change Log out with Inbox
driver.findElement(By.linkText("Inbox"));
Given the HTML:
Inbox
You need to take care of a couple of things here as follows:
Within cssSelector doesn't supports the :contains("text") method
Within xpath for exact text matches you need to use text()
Solution
To identify the element you can use either of the following locator strategies:
Using linkText:
WebElement element = driver.findElement(By.linkText("Log out"));
Using cssSelector:
WebElement element = driver.findElement(By.cssSelector("a[href$='INBOX'][title='View the Inbox']"));
Using xpath:
WebElement element = driver.findElement(By.xpath("//a[text()='Inbox' and #title='View the Inbox']"));

xPath Text Contains Selenium Web Driver

I'm trying to select an element based on its text contents. I am using XPath to achieve this.
I am just puzzled as this should work?
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
I'll even copy the HTML code:
<div class="linkWrap noCount">Notifications <span class="count _5wk0 hidden_elem uiSideNavCountText">(<span class="countValue fsm">0</span><span class="maxCountIndicator"></span>)</span></div>
The div element has the words "Notifications" inside it. So why doesn't it work.
Go to this page on Facebook: https://www.facebook.com/settings
Use this chrome extension to highlight any area via xPath.
You have a space before the word Notifications:
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
You should also add a wait for element before trying to find the element:
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(), 'Notifications')]"));
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
I found the issue with the help of some amazing people in this community.
Ok, so my element was in an iFrame.
In order to access the element, I must first access the iFrame
WebElement iframe = obj.driver.findElement(By.xpath("//iframe[#tabindex='-1']"));
obj.driver.switchTo().frame(iframe);

How to identify the first record in the virtual table with xpath or CSS selector

I have the following HTML code where I need to detect the number of records displayed on the page and select the correct record. However, inspecting the elements with Firefox show the records are having the same class name while the id of the WebElement is dynamically created.
If I use it to locate by tag name, it will return more than 100 Web elements.
May I know how do I identify use XPath or CSS selector to obtain the first record displayed on the page.
enter image description here
WebElement menuList = driver.findElement(By.cssSelector(".scrollable-content"));
List<WebElement> search_li = menuList.findElements(By.tagName("div"));
WebElement searchresult = driver.findElement(By.ByXPath.className("grid-view-drop-area ng-star-inserted"));
searchresult.click();
Thank you DebanjanB and Guy for your valueable input.
I used the combination of your input to get identify the unique UI object.
List<WebElement> searchresult = driver.findElements(By.xpath("//div[#class='scrollable-content']/div[#class='grid-view-drop-area ng-star-inserted' and starts-with(#id, 'grid-row')]"));
searchresult.get(0).click();
A bit of more information interms of the HTML of the expanded <div> tags would have helped us to construct a canonical answer. However, to extract the number of records displayed on the page you have to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use either of the following Locator Strategies:
cssSelector:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.grid-view-drop-area.ng-star-inserted[id^='grid-row']"))).size());
xpath:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[#class='grid-view-drop-area ng-star-inserted' and starts-with(#id, 'grid-row')]"))).size());
To obtain the first record you can use either of the following solution:
cssSelector:
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibility_of_element_located(By.cssSelector("div.scrollable-content>div.grid-view-drop-area.ng-star-inserted[id^='grid-row']")));
xpath:
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibility_of_element_located(By.xpath("//div[#class='scrollable-content']/div[#class='grid-view-drop-area ng-star-inserted' and starts-with(#id, 'grid-row')]")));

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.

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.

Categories