【问题标题】:Select radio button with dynamic Id, using CSS selector or Xpath使用 CSS 选择器或 Xpath 选择具有动态 ID 的单选按钮
【发布时间】:2020-09-27 13:59:44
【问题描述】:

我在 Visual Studio 中使用 C# 来选择多个是或否问题。下面是选择“是”的第一个按钮。 id 不是静态的,所以不能使用它,而且我不确定哪个路径(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>

【问题讨论】:

标签: c# visual-studio selenium-webdriver xpath css-selectors


【解决方案1】:

如果您更喜欢使用 XPath 或 CSS 选择器,则取决于手头的元素和个人喜好。 E. Wiest 链接的article 有一些优点。

在您的具体情况下,您可以使用 :checked 之类的 CSS 选择器

input[type='radio']:checked
  • 如果你想选择后面的label例如

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

或建议的一些 XPath

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

就个人而言,我也认为 XPath 更强大,但 CSS 选择器通常同样足够。

【讨论】:

    【解决方案2】:

    当您有动态 CSS Id、名称时,最好使用 Xpath。

    根据您的要求(“选择多个是或否问题”),您应该有一个关系 b/w Questions and option。

    您可以在两个元素之间建立 Xpath 关系,如下例所示。

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

    或者

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

    根据您的要求更新这些 Xpath

    【讨论】:

      猜你喜欢
      • 2020-06-17
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多