Reputation: 718
I have a drop down menu which changes its id after clicking it
Here is the HTML code before clicking on it (This code is grayed out {hidden} in page).
<a class="headet_fonts" href="http://192.168.1.6/eprint_prod_3.8/ProductCatalogue/PriceCatalogue.aspx" onmouseout="javascript:displaynone('#FFFFFF');" onmouseover="javascript:onhovermenu('ProductCatalogue/PriceCatalogue.aspx','Products','Products',tabcolor,headerforecolor)">
<b>
<span id="**ctl00_header1_upperRepeater_ctl10_ModuleName**" class="headet_fonts header_colorbalck" style="color:black;">
Products
</span>
<input id="ctl00_header1_upperRepeater_ctl10_hdn_Forecolor" type="hidden" value="#FFFFFF" name="ctl00$header1$upperRepeater$ctl10$hdn_Forecolor">
</b>
</a>
HTML code after clicking on it (This code is not hidden):
<a class="headet_fonts" href="http://192.168.1.6/eprint_prod_3.8/ProductCatalogue/PriceCatalogue.aspx" onmouseout="javascript:displaynone('#FFFFFF');" onmouseover="javascript:onhovermenu('ProductCatalogue/PriceCatalogue.aspx','Products','navbar',tabcolor,'#FFFFFF')">
<b>
<span id="ctl00_header1_upperRepeater_ctl10_ActiveModuleName" class="ActiveModulenavigatorpanel" style="color:#FFFFFF;">
Products
</span>
</b>
</a>
In Selenium code I used xpath:
//div[@id='Products']/a/b/span
to locate it but it is showing NoSuchElementException
. I can't use ID since it is changing
Upvotes: 0
Views: 1396
Reputation: 29032
I'm only providing this as an alternative: Use CSS not xpath. CSS is cleaner, simpler, and faster.
span[id^='ctl00_header1_upperRepeater']
I just can't condone the other answers. Xpath is complicated and unnecessary for something of this caliber.
Upvotes: 1
Reputation: 7008
From the html we can conclude that the anchor tag will be visible on onmouseover
event. So you just have to use Action
class movetoelement()
method to hover over the header.And then use findElement()
with
xpath = //div[@id='Products']//span[contains(.,'Products')]
or
Since its within an anchor tag, you can use linkText
as well :
driver.findElement(By.linkText("Products")).click();
One more simpler method would be to use JavascripExecuter
, using this you dont have to hover to make the element visible, because this will work on hidden elements as well, though i don't recommend this (reason - users wont click on hidden elements). The following script is just for your knowledge :
((JavascriptExecutor)driver).executeScript("$('div#Products span').click();");
Upvotes: 1
Reputation: 7227
Just use a different xpath, you are not limited to the one you showed.
You can use xpath's contains()
function, for example:
//span[contains(@id, 'ctl00_header1_upperRepeater_ctl10')]
Or try to select the span
via the a
tag:
//a[@class=='headset_fonts']//span
//a[contains(@href, 'ProductCatalogue/PriceCatalogue.aspx')]//span
For developing these xpaths, use something that immediately shows you results (e.g. the XPath Checker addon for Firefox). That way you should quickly arrive at a working xpath.
Upvotes: 1