Empiricist
Empiricist

Reputation: 126

C# Selenium Finding an element by a parameter of onclick() attribute

Okay I've got a set of elements that do not have consistent IDs but they do have a long onclick that has a unique identifier see below. These elements can overlap so I don't want to try a css style selector.

<a  href="#" onclick="fireEntrySelected('scheduleFrm',
'scheduleFrm:selectableClassType', '12345678901234567890123456789123_12');"
class="selectableClassType" style="position: absolute; height: 42px; 
top: 88px; left: 5%; width: 2%; padding: 0px; overflow: hidden; 
border-width: 1px; border-style: solid; border-color: rgb(255, 235, 205);
background-color: rgb(255, 235, 205); display: inline-block;"
id="__autoIdNumXwhereXchangingOnReloads">
<span class="title" style="line-height: 15px;">
Title information that can be repeated on the page</span>
</a>

I need to cycle through every one of these appointments so what I'd like to do is click it with something like:

 driver2.FindElement(By.XPath(@"//*[contains(onclick,'12345678901234567890123456789123_12')]")).click()

Which fails with no such element and I've verified the number shows up on there on the page and only one time. I'm using ChromeDriver in selenium on c#, so:

  1. What selector will get this element?
  2. What's wrong with my selector?
  3. Does anyone have a good resource for the C# selenium webdriver XPath selector I'm probably missing something obvious ,but I have not found good documentation.

on the plus side I realized I can just do the java call, so I have a hackish answer, but not a good one.

Upvotes: 0

Views: 4138

Answers (2)

Saurabh Gaur
Saurabh Gaur

Reputation: 23805

What selector will get this element?

As you've mentioned they do have a long onclick that has a unique identifier, So the best locator would be cssSelector to locate this element as below :-

 driver2.FindElement(By.XPath("a[onclick *= '12345678901234567890123456789123_12']")).Click();

What's wrong with my selector?

You xpath logically incorrect, you're missing to append @ before element attribute name, it should be as below :-

driver2.FindElement(By.XPath("//*[contains(@onclick,'12345678901234567890123456789123_12')]")).Click();

Does anyone have a good resource for the C# selenium webdriver XPath selector I'm probably missing something obvious ,but I have not found good documentation

Upvotes: 1

alecxe
alecxe

Reputation: 473813

You are missing the @ before the attribute name:

//*[contains(@onclick, '12345678901234567890123456789123_12')]
         HERE^

I don't think this is, generally speaking, a reliable locator, but to provide a better option, we should see the complete HTML of the page and know what information you have and can use to locate the element.

Upvotes: 1

Related Questions