简体   繁体   中英

Get ID of a radio button with Selenium CSS selector

I just wanted to know that how can I get the ID of

<input type="radio" class="class1" id="radio1" />

with the help of CSS selectors in Selenium.

This is a more difficult and intriguing question than you might suppose. It is important to be aware that values for the HTML class attribute are not unique . Thus, it is quite possible (and in fact probable) that your HTML page may have multiple elements with the class set to "class1". So selecting strictly on the class will only work if your radio button is the first element on your web page with that class value. Working only with your example, a safer locator expression would be

selenium.GetAttribute("css=input.class1[type='radio']@id");

This matches only class1 elements that are radio buttons. It is much more specific--it correctly avoids prior elements that happen to also have the class1 value for the class attribute. But it is still not satisfactory--again it will match the first such element. You can improve further if, for example, you have more than one group of radio buttons. Say you wanted the first radio button in the second group from this code fragment...

<div id='group1'>
  <input type="radio" class="class1" id="radio1" />
  ...
</div>
<div id='group2'>
  <input type="radio" class="class1" id="radio1" />
  ...
</div>

... you could use a locator like this:

selenium.GetAttribute("css=#group2 .class1[type='radio']@id");

(Note that the space after '#group2' is important!)

However, the above is mostly to explain the problem rather than to provide a good answer, because the fundamental problem remains.

Most likely your code is really something like this, with multiple radio buttons all having the same type and same class, distinguishable only by position:

<input type="radio" class="class1" id="radio1" />
<input type="radio" class="class1" id="radio2" />
<input type="radio" class="class1" id="radio3" />

The only way to target one of these other than the first is by explicit indexing, but that requires you know the index a priori , eg:

selenium.GetAttribute("css=#group2 [type='radio']:nth-child(2)@id");

(For more on constructing CSS recipes for Selenium see my article and wallchart XPath, CSS, DOM and Selenium: The Rosetta Stone on Simple-Talk.com.)

I will give you an example:

selenium.GetAttribute("css=.class1@id");

Here is the link for the documentation http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/dotnet/Selenium.DefaultSelenium.GetAttribute.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM