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);
Related
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']"));
I want to locate the "item1" div tag in the following DOM. I tried in different ways. But I could not make it happen.
<html></html>
<frameset ... >
<frame>
</frame>
<frame id= "dynamic value" name = "dynamic value">
<html >
<head></head>
<body>
<div name = "item1">
<div name = "item2">
So , I tried the following ways to locate it. But no such element exception was thrown.
driver.getElementsByTagName("frame")[1].getElementsByTagName("div")[0]
driver.swithTo().frame(1);
driver.getElementsByTagName("div")[0]
You should switch to frame before you search for an element.
Try this:
frame = driver.getElementsByTagName("frame")[1]
driver.swithTo().frame(frame);
driver.getElementsByTagName("div")[0]
Note, I am not sure what is getElementsByTagName(), it looks like some sort of custom method for findElement(), so I just copypasted it into my solution from your example.
getElementsByTagName() DOM method in JavaScript
Source
Seems like you are using wrong method to locate an element using tag name.
In Selenium Java, Use below code snippet to switch into frame
driver.swithTo().frame(1); // index = 1 means 2nd frame
driver.findElements(By.tagName("div"))[0]
And with ExplicitWait conditions (to avoid synchronization related issue)
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameName);
There are a couple of things you need to consider:
Using Selenium while dealing with <iframe> you can safely ignore the <frameset>
It would be difficult to identify the desired <iframe> through their index as it will be inconclusive which <iframe> loads faster.
As the the desired element is within an <iframe> so to locate the element you have to:
Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt().
Induce WebDriverWait for the desired visibilityOfElementLocated().
You can use either of the following Locator Strategies:
Using CSS_SELECTOR:
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe#dynamicValue[name='dynamicValue']")));
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[name='item1']")));
Using XPATH:
new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#id='dynamicValue' and #name='dynamicValue']")));
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#name='item1']")));
Reference
You can find a coupple of relevant discussions in:
Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?
Ways to deal with #document under iframe
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
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.
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.