Mary
Mary

Reputation: 23

How to click a dynamic element

I'm trying to figure out the xpath which retrieve the "Projects (x)" from the following html, but without any results:

<li class="">
    <span id="c1025_ctl">
        <a id="c1025">
            <span>Similar people</span>
        </a>
    </span>
</li>
<li class="tabs-selected">
    <span id="c1016_ctl">
        <a id="c1016">
            <span>Projects (x)</span>
        </a>
    </span>
</li>
<li class="">
    <span id="c1037_ctl">
        <a id="c1037">
            <span>Info</span>
        </a>
    </span>
</li>

I've tried so far with //a[contains(.,'Projects (x)')]/span and //a[contains(.,'Projects (x)')]

Upvotes: 0

Views: 47

Answers (2)

Aaron
Aaron

Reputation: 24812

If ids are known when crafting your XPath and are consistent, the following should be preferred :

//a[@id="c1016"]

If you can only make your search based on the text, you could use this :

//a[./span/text()="Projects (x)"]

I tested these on http://www.xpathtester.com/xpath where I successfully retrieved the target a tag after using your example data encapsulated in a root tag (in order to make it valid XML) ; I can't however share the results as the site's save function seems to remove everything from the XPath field after the first quote.

Concerning the Java code you added in a comment, I would try to invoke the By.xpath(...).toString() method hoping it would display the whole constructed XPath. This might point out errors in its construction. Note that I don't know Selenium and can only hope the By.toString method will behave this way.

If it doesn't, I'd use my IDE debugger to inspect the By item created by the invocation of By.xpath(...) and check out its fields, expecting to find one containing the whole constructed XPath.

Upvotes: 1

SomeDude
SomeDude

Reputation: 14238

You could try the xpath :

//span[. = 'Projects (x)'][parent::a]/parent::a if you want to get the element a,

Remove parent::a at the end if you want just span

Upvotes: 0

Related Questions