Selenium WebDriver Xpath current element attribute reports invalid Xpath exception - selenium

I have html like
<html>
<body>
<div class='open'>
<h1>Title</h1>
<div>Opened</div>
</div>
</body>
</html>
And in my Selenium WebDriver 3 tests I am trying to select the div.open element using the following xpath:
//h1/../.[contains(#class, 'open')]
In the following command in c#:
driver.FindElement(By.XPath("//h1/../.[contains(#class, 'open')]"));
Which results in
OpenQA.Selenium.InvalidSelectorException : invalid selector:
Unable to locate an element with the xpath expression //h1/../.[contains(#class, 'open')] because of the following error::
Failed to execute 'evaluate' on 'Document': The string '//h1/../.[contains(#class, 'open')]' is not a valid XPath expression.
Searching by the same Xpath in Firefox console successfully locates the element.
Any ideas why WebDriver considers this xpath invalid?
Note: my example is of course simplified

I would say that's probably down to the specification doesn't explicitly state whether predicate after abbreviated step i.e . and .. should be allowed, neither the specification ever mention an example involving predicate after abbreviated step.
So some XPath implementations just don't support it. One of these, I noticed, is XPath implementation in .NET framework. Other implementations explicitly disallow it, and even provide useful suggestion for the user to replace . or .. in their XPath with the equivalent unabbreviated expression, in order, self::node() or parent::node(), for example, the implementation used by xpathtester. But as you noticed, other implementations might support it.
As of workaround, there are many alternatives XPath which equivalent or close enough to you original attempted XPath. The easiest is to expand the . to its unabbreviated expression, as I mentioned above. Personally, I prefer not to go down the tree and then back up to return a parent element, if possible. Instead, just stop at the parent element which we want to return, and check for the child in predicate :
//*[contains(#class, 'open')][h1]

If you want to reference "div" with respect to "h1" tag then you can change the xpath to following:
//h1/ancestor::div[contains(#class, 'open')]

Instead of //h1/../.[contains(#class, 'open')] xpath can you try //div[#class='open'] xpath

Related

How to handle multiple xpath for same locator using Selenium?

How to handle multiple xpath for same locator using Selenium, i.e if one is failed use another locator for same field before failing script.
To start with each WebElement within the DOM Tree can be uniquely identified using any of the available Locator Strategies.
However, you can construct multiple xpath for the same element using permutation and combination of the available attributes and their values. As an example, for the element below:
<div class="_2S1VP copyable-text selectable-text" data-tab="1" dir="ltr" spellcheck="true" contenteditable="true"></div>
You can construct multiple xpaths as follows:
"//div[contains(#class, 'copyable-text')]"
"//div[contains(#class, 'copyable-text') and #data-tab='1']"
"//div[contains(#class, 'copyable-text') and #data-tab='1'][#dir='ltr']
"//div[contains(#class, 'copyable-text') and #data-tab='1'][#dir='ltr' and #spellcheck='true']"
"//div[contains(#class, 'copyable-text') and #data-tab='1'][#contenteditable='true']"
All these xpaths would identify the same element. But what matters most is the xpath should be able to identify the desired element uniquely. The responsibility of constructing the optimized xpath is solely on the test creator.
Use OR expression for the same. You can pass multiple attribute of the same WebElement.
For example:
Xpath=//*[#type='submit' or #name='btnReset']

Can't find unique xpath for clickable element

I'm trying to get an xpath so I can click a link as per href below:
<div id="viewIFL" style="">
<div class="moneycentrallink">
Track your cash in one place with
Money Central
</div>
</div>
When I use the below in ChroPath:
//a[contains(text(),'Money Central')]
It returns 2 elements matching for xpath="1" and xpath="2".
I then tried:
//a[contains(text(),'Money Central') and #xpath='2']
and at first it resolved to just 1 element found but when I tried searching again it returned 0 elements found. Also this does not work via Selenium either (returns unable to find element).
Any ideas what's going on and how I can find the unique xpath to clickable element? Thanks
Don't use xpath attribute in your xpath as ChroPath adds the xpath attribute in element to tell the user what is matching occurrence of that element. For example- If ChroPath added xpath=5 i.e. this element is the 5th for the corresponding xpath.
For your scenario, please inspect the element and see what ChroPath gives the relative xpath.
Also you can try //div[contains(text(),'Track your cash')]//a[contains(text(),'Money Central')]
Your problem is badly formulated.
There is always a unique path to an element of the form *[1]/*[4]/*[1]/*[2]. The problem is that this path isn't very useful because it only works if you know exactly what is in the document, and if you knew exactly what was in the document, you wouldn't need XPath to find it.
So you're actually looking for an XPath that will work on a set of possible documents in which some parts are known (fixed) and others are unknown (variable). To find an XPath that works on every document in that set, you need to define what is known and what is unknown. Looking at one sample document isn't going to tell you that.

Is it okay to use such xpath to find web elements?

Consider this xpath which should always return one element.
//div[#id='MyDiv123']/div[contains(#class, 'super')]
Assume that we won't add anymore divs whose class is super. Given that info, I don't think that it is a good idea to use /div[contains(#class, 'super')]because the xpath will break if div[contains(#class, 'super')] is placed inside another element.
Shouldn't we be using //div[contains(#class, 'super')] instead ?
I don't like using XPaths for locators that can be written as a CSS selector. I think it's much simpler as
#MyDiv123 > div.super
or just
div.super
if it's unique on the page.
XPath contains() is a string match. All the elements below will match your XPath locator but none of them will match the CSS selectors above.
<div class="super-duper" ...>
<div class="superior" ...>
<div class="abcsuperdef" ...>
... you get the idea...
There is no defined Best Practices while writing xpaths. It all boils down to how effective xpath can be written.
I don't see any issue with the xpath as :
//div[#id='MyDiv123']/div[contains(#class, 'super')]
Of-coarse there ca be some improvements as follows :
As an enduser you won't be sure how the class attribute super impacts the HTML or which elements have this attribute. So in that case to identify the WebElement uniquely it would be wise to include the ancestor <div> tag with id as MyDiv123.
But it doesn't looks like the classname super can be dynamic. Hence you can avoid the keyword contains within the xpath and rewrite it as :
//div[#id='MyDiv123']/div[#class='super']

How to get value from an attribute in selenium RC in java?

I have this code for xpath and html:
<a class="WatchButton inicon" rel="nofollow" data-productid="111124">
xpath=/html/body/div[2]/div[2]/div/div[2]/div[1]/div[1]/div[2]/div[8]/a
How can I get the data-productid value?
Just add #data-productid to the xpath expression:
/html/body/div[2]/div[2]/div/div[2]/div[1]/div[1]/div[2]/div[8]/a/#data-productid
Note that the xpath expression you have is very fragile since it depends on a bunch of elements and their relevant positions. Try to rely on the element's attributes or one of it's containers - look for id and class attributes. For example:
//a[contains(#class, "WatchButton")]/#data-productid
This gets the first link anywhere on a page that contains WatchButton class and retrieves it's data-productid attribute value.
* Sharing the link to the web page or showing the complete HTML could help to provide you with a more reliable xpath expression.

how to locate element with selenium webdriver for below html

I have an issue clicking on the below HTML:
<div id="P7d2205a39cb24114b60b80b3c14cc45b_1_26iT0C0x0" style="word-wrap:break-word;white-space:pre-wrap;font-weight:500;" class="Ab73b430b430a49ebb0a0e8a49c8d71af3"><a tabindex="1" style="cursor:pointer;" onclick="var rp=$get('ctl00_ContentPlaceHolder1_ReportViewer1_ctl10_ReportControl');if(rp&&rp.control)rp.control.InvokeReportAction('Toggle','26iT0C0x0');return false;" onkeypress="if(event.keyCode == 13 || event.which == 13){var rp=$get('ctl00_ContentPlaceHolder1_ReportViewer1_ctl10_ReportControl');if(rp&&rp.control)rp.control.InvokeReportAction('Toggle','26iT0C0x0');}return false;"><img border="0" src="/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=10.0.30319.1&Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.TogglePlus.gif" alt="+"></a> 2013</div>
I have used the below script to click anchor inside a div tag. For the above html code it is not fixed only end part of id example "26iT0C0x0" is fixed. The script that I have used is:
WebElement e1=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[ends-with(#id,'26iT0C0x0')]/a")));
e1.click();
You can use the 'contains' method within an xpath lookup:
driver.findElement(By.xpath("//div[contains(#id,'26iT0C0x0')]")
I would recommend you to consider CSS selector alternative as CSS working faster, than xpath.
So 'contains' in attribute in CSS stands for '*=', for example
if we want to find attribute by 'CSS' ending in this: <htmlTag A="blablaCSS" > we need do the following:
String CSSselector="htmlTag[A*=CSS]";
and you get this element searched.
So considering your example CSS selector be like:
String cssSearched="div[id*=26iT0C0x0] a";
also try to click not on link - a
but on parent div as well:
String cssSearched="div[id*=26iT0C0x0]";
driver.findElement(By.cssSelector(cssSearched));
hope this works for you.
As Mark Rwolands already mentioned: the xpath-Function 'ends-with()' isn't supported in Selenium 2.
Also, if you maybe consider to use chromeDriver in the future, I would recommend clicking the image, not the anchor, see:
https://sites.google.com/a/chromium.org/chromedriver/help/clicking-issues
edit:
Also your IDs are looking generated. I wouldn't count on them for a stable test-environment.