简体   繁体   English

Select 带有动态 ID 的单选按钮,使用 CSS 选择器或 Xpath

[英]Select radio button with dynamic Id, using CSS selector or Xpath

I'm using C# in Visual Studio to select multiple yes or no questions.我在 Visual Studio 中使用 C# 到 select 多个是或否问题。 Below is the first button to select "yes".下面是 select“是”的第一个按钮。 The id is not static so can't use that, and I'm not sure which path (CSS or Xpath) is the most efficient for this route. id不是 static 所以不能使用它,我不确定哪个路径(CSS 或 Xpath)对这条路线最有效。

<div class="row form-group">
  <label class="form-label col-md-4 col-lg-3">Was everything satisfactory?</label>
  <div class="col-md-7 col-lg-8"><fieldset class="form-group form-radio-group" id="__BVID__385">
    <div tabindex="-1" role="group"><div role="radiogroup" tabindex="-1" class="" id="__BVID__386">
      <div class="custom-control custom-control-inline custom-radio">
        <input type="radio" autocomplete="off" class="custom-control-input" value="true" id="__BVID__387" name="__BVID__386">
        <label class="custom-control-label" for="__BVID__387">Yes</label>
      </div>
    </div>
  </div>

If you are better of using XPath or CSS selector comes down to the element at hand and personal preferences.如果您更喜欢使用 XPath 或 CSS 选择器,则取决于手头的元素和个人喜好。 The article linked by E. Wiest has some good points. E. Wiest链接的文章有一些优点。

In your concrete case, you can either use a CSS selector like :checked在您的具体情况下,您可以使用 CSS 选择器,例如:checked

input[type='radio']:checked
  • if you want to select the subsequent label for instance如果你想 select 例如后续的label

     input[type='radio']:checked+label

Or some XPath as suggested或建议的一些 XPath

//label[contains(text(), "Yes")]/preceding::input

Personally, I also consider XPath to be more powerful but a CSS selector is usually equally adequate.就个人而言,我也认为 XPath 更强大,但 CSS 选择器通常同样足够。

Its best to use Xpath when you have dynamic CSS Ids, name.当您有动态 CSS Ids、名称时,最好使用 Xpath。

Based on your requirement ('select multiple yes or no questions') you should have a relation b/w Questions and option.根据您的要求(“选择多个是或否问题”),您应该有一个关系 b/w 问题和选项。

you can make a Xpath relationship between two elements like in below samples.您可以在两个元素之间建立 Xpath 关系,如下面的示例所示。

//label[contains(.,'Was everything satisfactory?')]/following-sibling::div/fieldset/div/div/div/label[.='Yes' or .='No']

Or或者

//label[.='Yes' or .='No']/ancestor::div/parent::body/label[contains(.,'Was everything satisfactory')]

Update these Xpaths as per your requirement根据您的要求更新这些 Xpath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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